题目链接:https://leetcode.com/problems/single-number-ii/description/

题目大意:给出一串数,每个数都出现三次,只有一个数只出现一次,把这个出现一次的数找出来。

法一:利用hashMap,空间换时间,但是好像也没怎么换到时间。代码如下(耗时15ms):

 1     public int singleNumber(int[] nums) {
 2         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 3         int ans = -1;
 4         for(int i = 0; i < nums.length; i++) {
 5             if(map.containsKey(nums[i])) {
 6                 map.put(nums[i], map.get(nums[i]) + 1);
 7             }
 8             else {
 9                 map.put(nums[i], 1);
10             }
11         }
12         for(int i = 0; i < nums.length; i++) {
13             if(map.get(nums[i]) == 1) {
14                 ans = nums[i];
15                 break;
16             }
17         }
18         return ans;
19     }
View Code

相关文章:

  • 2021-11-29
  • 2022-12-23
  • 2021-08-13
  • 2022-02-10
  • 2022-02-22
  • 2022-12-23
  • 2022-01-06
猜你喜欢
  • 2022-02-04
  • 2021-10-14
  • 2022-03-04
  • 2021-08-12
  • 2021-09-20
相关资源
相似解决方案