剑指offer 39:数组中只出现一次的数

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

Map去重

思路:

  1. 只要重复就跳过不记录,反之只出现一次的都记录下来,出现两次的删除
  2. 选择结构来记录,并且到时候方便查重和遍历取出

缺点:

  1. 利用了map初始化堆栈里占空间
  2. 遍历耗时
//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<Integer,Integer>();
        for(int i=0;i<array.length;i++){
            if(map.get(array[i])!=null){
                map.remove(array[i]);
            }else{
                map.put(array[i],array[i]);
            }
        }
        int j=0;
        for (Integer value  : map.values()) {
           array[j++]=value;
        }
        num1[0]=array[0];
        num2[0]=array[1];
    }
}
发布了105 篇原创文章 · 获赞 19 · 访问量 4967

猜你喜欢

转载自blog.csdn.net/jiohfgj/article/details/104974835
今日推荐