"Sword Finger Offer"-40, a number that only appears once in the array

1. Knowledge points of this question

Hash table

2. Title description

Except for two numbers in an integer array, the other numbers appear twice. Please write a program to find these two numbers that only appear once.

3. Problem solving ideas

  1. Use HashMap to create a mapping between each number and its number of occurrences
  2. Traverse the string in turn, find the first number with 1 occurrence, and add it to the array

4. Code

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    
    
    public void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
    
    
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int count = 0;
        // 用 HashMap 建立每个数字与其出现次数的映射
        for (int i : array) {
    
    
            hashMap.put(i, hashMap.getOrDefault(i, 0) + 1);
        }
        // 依次遍历字符串,找到第一个出现次数为 1 的数字,并加入数组中
        for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
    
    
            if (entry.getValue()== 1) {
    
    
                if (count == 0) {
    
    
                    num1[0] = entry.getKey();
                    count++;
                } else {
    
    
                    num2[0] = entry.getKey();
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/113050766