数组中数字出现的次数

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

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     # 返回[a,b] 其中ab是出现一次的两个数字
 4     def FindNumsAppearOnce(self, array):
 5         diff = 0
 6         for num in array:
 7             diff ^= num
 8         diff &= -diff
 9         num1 = [0]
10         num2 = [0]
11         for num in array:
12             if num & diff == 0:
13                 num1[0] ^= num
14             else:
15                 num2[0] ^= num
16         return [num1[0],num2[0]]
17         # write code here

 

Java版代码,leetcode地址

 1 class Solution {
 2     public int[] singleNumbers(int[] nums) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         HashSet<Integer> set = new HashSet<>();
 5         int n = nums.length;
 6         for(int i=0;i<n;i++) {
 7             if(map.containsKey(nums[i])) {
 8                 int count = map.get(nums[i]);
 9                 count++;
10                 map.put(nums[i], count);
11                 if(set.contains(nums[i])) {
12                     set.remove(nums[i]);
13                 }
14             }else {
15                 map.put(nums[i], 1);
16                 set.add(nums[i]);
17             }
18         }
19         Integer[] resultIntegers = set.toArray(new Integer[2]);
20         int[] result = new int[resultIntegers.length];
21         for(int i=0;i<resultIntegers.length;i++) {
22             result[i] = resultIntegers[i];
23         }
24         return result;
25     }
26 }

 

 

56_2题:

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

Java版代码,leetcode地址

 1 class Solution {
 2     public int singleNumber(int[] nums) {
 3         HashMap<Integer, Integer> map = new HashMap<>();
 4         HashSet<Integer> set = new HashSet<>();
 5         int n = nums.length;
 6         for(int i=0;i<n;i++) {
 7             if(map.containsKey(nums[i])) {
 8                 int count = map.get(nums[i]);
 9                 count++;
10                 map.put(nums[i], count);
11                 if(set.contains(nums[i])) {
12                     set.remove(nums[i]);
13                 }
14             }else {
15                 map.put(nums[i], 1);
16                 set.add(nums[i]);
17             }
18         }
19         Integer[] resultIntegers = set.toArray(new Integer[1]);
20         return resultIntegers[0];
21     }
22 }

 

posted on 2019-06-14 17:33  Sempron2800+  阅读(202)  评论(0编辑  收藏  举报