騰訊//只出現一次的數字
阿新 • • 發佈:2018-12-23
給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的演算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?
示例 1:
輸入: [2,2,1] 輸出: 1
示例 2:
輸入: [4,1,2,1,2] 輸出: 4
class Solution { public int singleNumber(int[] nums) { Arrays.sort(nums); for(int i = 0; i < nums.length; i+=2){ if(i + 1 >= nums.length) return nums[i]; if(nums[i] != nums[i+1]) return nums[i]; } return -1; } }
class Solution { public int singleNumber(int[] nums) { Set<Integer> set = new HashSet<>(); for(int i = 0; i < nums.length; i++){ if(!set.add(nums[i])){ //add成功返回true,如果set中已有相同數字,則會返回false set.remove(nums[i]); //刪除重複出現的數字 } } return set.iterator().next(); } }
class Solution {
public int singleNumber(int[] nums) {
int num = 0;
for(int i = 0; i < nums.length; i++){
num = num ^ nums[i];
}
return num;
}
}
通用解法,當有多個重複時:
private static List<int> FindSingleNumber2(int[] nums) { List<int> repeatNums = new List<int>();//宣告一個集合 Array.Sort(nums);//繼續排序 for (int i = 0; i < nums.Length;) { if (i + 1 >= nums.Length) { repeatNums.Add(nums[i]);//找到不一樣的就新增到集合 break;//執行到這裡肯定最後一個,直接打斷跳出 } if (nums[i] == nums[i + 1]) { i = i + 2;//有一對相同的就加2繼續迴圈遍歷 } else { repeatNums.Add(nums[i]);//找到不一樣的就新增到集合 i = i + 1;//沒有相同的就加1好了 } } return repeatNums;//返回集合 }