|
| 1 | +## 137. 只出现一次的数字 II |
| 2 | +> https://leetcode-cn.com/problems/single-number-ii/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-08-16 14:34:53 |
| 10 | + * @LastEditTime: 2020-08-16 14:51:09 |
| 11 | + * @Description: https://leetcode-cn.com/problems/single-number-ii/ |
| 12 | + * @FilePath: \leetcode-googtech\#102. Binary Tree Level Order Traversal\137.只出现一次的数字-ii.java |
| 13 | + * @WebSite: https://algorithm.show/ |
| 14 | + */ |
| 15 | + |
| 16 | +/* |
| 17 | + * @lc app=leetcode.cn id=137 lang=java |
| 18 | + * |
| 19 | + * [137] 只出现一次的数字 II |
| 20 | + */ |
| 21 | + |
| 22 | +// @lc code=start |
| 23 | +class Solution { |
| 24 | + public int singleNumber(int[] nums) { |
| 25 | + // 初始化 Map 集合 |
| 26 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 27 | + // 将数组中的元素作为key,其出现的次数作为value存储到 hashMap 中 |
| 28 | + // getOrDefault:若该元素不存在则返回0,反之返回对应数值出现次数并加1 |
| 29 | + for(int num : nums) { |
| 30 | + map.put(num, map.getOrDefault(num, 0) + 1); |
| 31 | + } |
| 32 | + // 遍历map的键值对,若键对应的值为1则返回该键,即结果数值 |
| 33 | + for(int key : map.keySet()) { |
| 34 | + if(map.get(key) == 1) { |
| 35 | + return key; |
| 36 | + } |
| 37 | + } |
| 38 | + // 无果 |
| 39 | + return -1; |
| 40 | + } |
| 41 | +} |
| 42 | +// @lc code=end |
| 43 | +``` |
| 44 | + |
| 45 | +### Python |
| 46 | +```python |
| 47 | +''' |
| 48 | +Author: Goog Tech |
| 49 | +Date: 2020-08-16 14:45:27 |
| 50 | +LastEditTime: 2020-08-16 14:52:02 |
| 51 | +Description: https://leetcode-cn.com/problems/single-number-ii/ |
| 52 | +FilePath: \leetcode-googtech\#102. Binary Tree Level Order Traversal\137.只出现一次的数字-ii.py |
| 53 | +WebSite: https://algorithm.show/ |
| 54 | +''' |
| 55 | +# |
| 56 | +# @lc app=leetcode.cn id=137 lang=python |
| 57 | +# |
| 58 | +# [137] 只出现一次的数字 II |
| 59 | +# |
| 60 | + |
| 61 | +# @lc code=start |
| 62 | +class Solution(object): |
| 63 | + def singleNumber(self, nums): |
| 64 | + """ |
| 65 | + :type nums: List[int] |
| 66 | + :rtype: int |
| 67 | + """ |
| 68 | + # 将数组中的元素作为key,其出现的次数作为value存储到 hashMap 中 |
| 69 | + hashMap = Counter(nums) |
| 70 | + # 遍历键值对,若键对应的值为1则返回改键,即结果数值 |
| 71 | + for k in hashMap.keys(): |
| 72 | + if hashMap[k] == 1: return k |
| 73 | + # 无果 |
| 74 | + return -1 |
| 75 | +# @lc code=end |
| 76 | +``` |
0 commit comments