540. Single Element in a Sorted Array Difficulty:Medium
2017-10-11 20:33
513 查看
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:
Example 2:
Note: Your solution should run in O(log n) time and O(1) space.
算法分析:已知要用O(log n)的时间复杂度的算法,那么这里选择用二分法。用left, mid, right表示左中右三点的下标,要有孤立值,数组长度是奇数,那么情况有三种:孤立值在左边,孤立值在中间,孤立值在右边。当孤立值在左边的时候,mid为偶数;当孤立值在右边的时候mid为奇数,分别对应前面的两个例子,具体见代码。Python和C类似,在此只列出C。
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(log n)的时间复杂度的算法,那么这里选择用二分法。用left, mid, right表示左中右三点的下标,要有孤立值,数组长度是奇数,那么情况有三种:孤立值在左边,孤立值在中间,孤立值在右边。当孤立值在左边的时候,mid为偶数;当孤立值在右边的时候mid为奇数,分别对应前面的两个例子,具体见代码。Python和C类似,在此只列出C。
int singleNonDuplicate(int* nums, int numsSize) { int left = 0, right = numsSize - 1, mid, i; while(left < right) { mid = (left + right) / 2; if(mid % 2 == 1) mid--; if(nums[mid] != nums[mid + 1]) //孤立值在左边 right = mid; else //孤立值在右边 left = mid + 2; } return nums[left]; }
相关文章推荐
- LeetCode 540. Single Element in a Sorted Array (Medium)
- 【LeetCode】540. Single Element in a Sorted Array 解题报告
- LeeCode 540. Single Element in a Sorted Array
- lettcode:540. Single Element in a Sorted Array(已排序数组中出现一次的数字,其他数字出现两次)
- (Java) LeetCode 540. Single Element in a Sorted Array —— 有序数组中的单一元素
- 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- LeetCode 540. Single Element in a Sorted Array
- leetcode 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- python--leetcode540. Single Element in a Sorted Array
- leetcode 540. Single Element in a Sorted Array
- 【LeetCode】540. Single Element in a Sorted Array
- LeetCode 540. Single Element in a Sorted Array
- 540. Single Element in a Sorted Array
- [LeetCode] 540. Single Element in a Sorted Array
- LeetCode 540. Single Element in a Sorted Array
- [Leetcode] 540. Single Element in a Sorted Array 解题报告
- LeetCode | 540. Single Element in a Sorted Array
- [LeetCode]540. Single Element in a Sorted Array