136. Single Number
阿新 • • 發佈:2021-12-14
Given a non-emptyarray of integers nums, every element appears twice except for one. Find that single one.
You mustimplement a solution with a linear runtime complexity and useonly constantextra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Each element in the array appears twice except for one element which appears only once.
解法:
- 找出只出現1次的數,首先想到的是將陣列排序,這樣通過比較相鄰數是否相等,即可找出來
- 建立一個Hashmap,當Hashmap中不存在某個數時,將其加入;當存在某個數時,將其刪掉。最後的Hashmap中會僅剩下一個數,而這個數!就是答案。
想法美滋滋,Hashmap yyds,
public static int singleNumber(int[] nums) { Map<Integer, Integer> num = new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++){ if(null == num.get(nums[i])){ num.put(nums[i], 1); }else { num.remove(nums[i]); } } for(int result: num.keySet()){ return result; } return 0; }
結果就一般,需要查一下時間複雜度和空間複雜度
3. 評論區看到:因為有“只有一個數字出現1次,其餘均出現兩次”————異或!
妙,妙不可言。
大聲喊出:交換律!結合率!自反性!