Single Number IV
Description
Give an array, all the numbers appear twice except one number which appears once and all the numbers which appear twice are next to each other. Find the number which appears once.
1 <= nums.length < 10^4
In order to limit the time complexity of the program, your program will run 10^5 times.
Have you met this question in a real interview?
Example
Given nums = [3,3,2,2,4,5,5], return 4.
Explanation:
4 appears only once.
Given nums = [2,1,1,3,3], return 2.
Explanation:
2 appears only once.
public class Solution {
/**
* @param nums: The number array
* @return: Return the single number
*/
//check mid odd or even.
// if mid is even, which means the numbers of element before mid is even(array index start from 0)
// then check the number before mid, if mid == mid-1,then there, the numbers left is totally odd which means
//the target number is before mid, then let right = mid. if mid != mid-1, becasue there is only one single number,
//which means the target is not before mid, then let left = mid
// if mid is odd, if mid == mid -1, then there are even numbers left, then let left == mid. if mid == mid-1, then let right = mid
public int getSingleNumber(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0, right = nums.length-1;
while(left+1<right){
int mid = left + (right - left)/2;
if (mid % 2 == 0) {
if (nums[mid] == nums[mid -1]) {
right = mid;
}else{
left = mid;
}
}else{
if (nums[mid] == nums[mid-1]) {
left = mid;
}else{
right = mid;
}
}
}
if (left > 0 && nums[left] != nums[left-1] && nums[left] != nums[left+1]) {
return nums[left];
}
return nums[right];
}
}
Last updated