Sword refers to Offer-37-a number that appears only once in the array

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.

Idea analysis

Directly use a hashmap to store the value and the number of occurrences, and then traverse again to get the result. Note that the results need to be stored in two arrays, num1 and num2, respectively. Therefore, it is necessary to set an amount to distinguish them, so that the code that is executed sequentially is loaded in two times in a loop.

Code

import java.util.HashMap;
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    
    
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
    
    
        //先将其排序
        if(array==null||array.length==0) return;
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i<array.length;i++){
    
    
            if(map.containsKey(array[i]))
                map.put(array[i],2);
            else
                map.put(array[i],1);
        }
        int flag = 0;//用于将num1和num2的添加数的操作分开
        for(int i = 0;i<array.length;i++){
    
    
            if(map.get(array[i])==1){
    
    
                if(flag==0){
    
    
                    num1[0] = array[i];
                    flag++;
                }
                else{
    
    
                    num2[0] = array[i];
                 }
              }
        }
    }
}

Why is there no need to carry out i++ after if so that the number already stored in num1 is skipped directly? Because if i is the last element, i++ is out of bounds here.

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107435442