剑指offer——数组中只出现一次的数字

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

解题思路:

现在做题真是越来越有感觉了,当出现什么数组中找一次两次啊什么的,优先考虑HashMap。

如果没出现这个值,那么就传入<key,1>。

如果出现了,value++;

 1 //num1,num2分别为长度为1的数组。传出参数
 2 //将num1[0],num2[0]设置为返回结果
 3 import java.util.HashMap;
 4 public class Solution {
 5     public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
 6         
 7         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
 8         
 9         for(int i=0;i<array.length;i++)
10         {
11             if(map.containsKey(array[i]))
12             {
13                 int value = map.get(array[i]);
14                 map.put(array[i],++value);
15             }
16             else
17             {
18                 map.put(array[i],1);
19             }
20         }
21         
22         for(int i=0;i<array.length;i++)
23         {
24             if(map.get(array[i])==1)
25             {
26                 num1[0]=array[i];
27                 break;
28             }
29         }
30         
31         for(int j=array.length-1;j>=0;j--)
32         {
33             if(map.get(array[j])==1)
34             {
35                 num2[0]=array[j];
36                 break;
37             }
38         }
39         return ;
40         
41         
42     }
43 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10872585.html