在一個數組 nums 中除一個數字只出現一次之外,其他數字都出現了三次。請找出那個只出現一次的數字。
2,示例描述示例 1:
輸入:nums = [3,4,3,3]
輸出:4
示例 2:
輸入:nums = [9,1,7,9,7,9,7]
輸出:1
限制:
1 <= nums.length <= 10000
1 <= nums[i] < 2^31
3,題解思路基於hashmap鍵值對集合
4,題解程序
import java.util.HashMap;
import java.util.Map;
public class SingleNumberTest5 {
public static void main(String[] args) {
int[] nums = {3, 4, 3, 3};
int singleNumber = singleNumber(nums);
System.out.println("singleNumber = " + singleNumber);
}
public static int singleNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
return map.entrySet()
.stream()
.filter(x -> x.getValue() == 1)
.findFirst()
.get()
.getKey();
}
}
5,總結一下對於本題,整體最容易理解的思路就是基於鍵值對集合hashmap進行解決了
歷史文章目錄數據結構:王同學下半年曾寫過的JDK集合源碼分析文章匯總
算法匯總:leetcode刷題匯總(非最終版)
Long-press QR code to transfer me a reward
感謝遇到的你
As required by Apple's new policy, the Reward feature has been disabled on Weixin for iOS. You can still reward an Official Account by transferring money via QR code.