540. Single Element in a Sorted Array
阿新 • • 發佈:2018-06-26
AS else 應用 移動 有一個 TP and except div
問題描述:
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.
解題思路:
要求我們要在O(logn)時間和O(1)空間內解決,首先想到二分搜索。
在二分搜索的應用中,如何找到移動的條件是十分關鍵的。
我們先觀察一下:
值: 1 1 2 2 4 4 5 5 9
下標: 0 1 2 3 4 5 6 7 8
此時中值為4,下標也為4。
若從頭到尾都是成雙成對,那偶數位的應該等於它後面的奇數位。
如果不等於,那麽說明前半段出現了一個奇數。
若中值位一個奇數,若它與前面的數字相同,則說明前面都是成雙成對,只有一個的數字是出現在後面。
同時我們也需要判斷當前值是否是我們要找的值
即不等於左邊的值,又不等於右邊的值
if((nums[mid] != l_Num || mid == 0) && (nums[mid] != r_Num || mid == n-1)){
return nums[mid];
}
在這裏需要註意的是數組頭部和尾部的判斷,否則會出現死循環
代碼:
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int n = nums.size(); if(n == 1) return nums[0]; int left = 0; int right = n-1; int mid; while(left <= right){ mid= left + (right - left)/2; int l_Num = mid-1 > -1 ? nums[mid-1] : nums[mid]; int r_Num = mid + 1 < n ? nums[mid+1] : nums[mid]; if((nums[mid] != l_Num || mid == 0) && (nums[mid] != r_Num || mid == n-1)){ return nums[mid]; } if(mid % 2 == 1){ if(l_Num == nums[mid]){ left = mid+1; }else{ right = mid; } }else{ if(l_Num == nums[mid]){ right = mid; }else{ left = mid+1; } } } return nums[mid]; } };
540. Single Element in a Sorted Array