Offer forty prove safety: an array of numbers appears only once

Casual working

In addition to an array of integers in two numbers, the other numbers appear twice. Please write a program to find these two figures appear only.

Thinking

Also use to map the set (a good map collection Dafa)

Code

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果'
import java.util.*;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<array.length;i++){
            map.put(array[i],map.containsKey(array[i])? map.get(array[i])+1:1);
        }
        int p=0;
        for(int i=0;i<array.length;i++){
            if(map.get(array[i])==1&&p==0){
                p=1;
                num1[0]=array[i];
            }
            if(map.get(array[i])==1)
            
                num2[0]=array[i];            
                
            
        }
    }
}
Published 61 original articles · won praise 38 · views 4575

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105377143