[LeetCode] Single Element in a Sorted Array
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2:
Input: [3,3,7,7,10,11,11] Output: 10
Note: Your solution should run in O(log n) time and O(1) space.
給定一個排好序的數組,其中每個元素出現兩次,只有一個元素出現一次,找出這個出現一次的元素。
題目要求run in O(log n) time and O(1) space
如果不按照題目要求,這是一個很簡明的算法題。給出3個算法如下:
1、順序遍歷,O(n) time
class Solution { public: int singleNonDuplicate(vector<int>& nums) { for (int i = 0; i < nums.size(); i = i + 2) { if (nums[i + 1] - nums[i] != 0) return nums[i]; } } }; // 7 ms
2、使用一個map存儲元素出現的次數,返回出現1次的元素 O(n) time and O(n) space
class Solution { public: int singleNonDuplicate(vector<int>& nums) { unordered_map<int, int> m; for (auto num : nums) m[num]++; for (auto it = m.begin(); it != m.end(); it++) if (it->second == 1) return it->first; } }; // 10 ms
3、使用異或來找出出現一次的元素。 O(n) time and O(1) space
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int res = 0; for (auto& num : nums) res ^= num; return res; } }; // 7 ms
以上三種算法雖然不滿足復雜度要求,但是完全可以AC。
4、使用二分搜索來查找元素。符合題意 O(log n) time and O(1) space
那個單獨出現的元素所在的索引一定是偶數。利用這個性質來二分搜索
如果mid是偶數,並且mid與mid+1的元素值相同,說明單獨的元素在mid的後面。
如果mid是奇數,並且mid和mid-1的元素值相同,說明單獨的元素在mid的後面。
舉個例子一看便知。
2 2 3 3 5 5 7
1 2 2 3 3 5 5
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int lo = 0, hi = nums.size() - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (mid % 2 == 0) { if (nums[mid] == nums[mid + 1]) lo = mid + 2; else hi = mid; } else { if (nums[mid] == nums[mid - 1]) lo = mid + 1; else hi = mid - 1; } } return nums[lo]; } }; // 7 ms
[LeetCode] Single Element in a Sorted Array