[编程题] nk:[数组中只出现一次的数字]

[编程题] nk:数组中只出现一次的数字

image-20200730003718615

输入输出

思路

方法1:借助两个set集合

方法2:借助栈

Java代码(方法1)

 /*方法1:set集合
         拿两个set集合,在遍历的时候如果第一次出现的元素就直接放入set集合,当第二次出现都放在set2中,放完之后从set中排序set2中
    含有元素,set中剩下的两个元素就是num1[],和num2[]*/
     public void FindNumsAppearOnce1(int [] array,int num1[] , int num2[]) {
        HashSet<Integer> set = new HashSet<>();
        HashSet<Integer> set2 = new HashSet<>();
        for(int i=0;i<array.length;i++){
            if(!set.add(array[i])){
                set2.add(array[i]);
            }
        }
        for(Integer i:set2){ set.remove(i); }
        int count=0;
        for(Integer i : set){
            if(count==0){  num1[0] = i; count++;}
            num2[0] = i;
        }
    }

Java方法(方法2:借助栈)

/*方法2:借用栈,先对数组排序处理。栈中初始放入数组的第一个元素。在从下标1处开始遍历时候每遍历一个
    元素就拿出对头匹配看是否和此相等,相等就出栈不相等就把该元素入栈,最终遍历完元素后,
    栈中剩余的两个元素就是出现一次的元素*/
    public static void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        //
        Arrays.sort(array);
        Deque<Integer> stack = new LinkedList<Integer>();
        stack.push(array[0]);
        for(int i=1;i<array.length;i++){
            if(stack.peek()!=null && stack.peek()==array[i]){
                stack.pop();
            }else{
                stack.push(array[i]);
            }
        }

        while(!stack.isEmpty()){
            num1[0] = stack.pop();
            num2[0] = stack.pop();
        }
}
原文地址:https://www.cnblogs.com/jiyongjia/p/13401551.html