540 Single Element in a Sorted Array
1. Question
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.
2. Implementation
(1) Binary Search
思路:用二分法的思想,中点mid,有三种情况 1. 如果nums[mid - 1] == nums[mid], 判断mid - 2 + 1(因为数组从0开始)是否奇数,如果是,则出现一次的数在[start, mid - 2]之间,否则在[mid + 1, end]之间
和情况一类似,如果nums[mid] == nums[mid + 1] ,判断mid - 1 + 1是否奇数,是的话则答案在[start, mid - 1]之间,否则在[mid + 2, end]之间
情况三,当nums[mid] != nums[mid - 1] 且 nums[mid] != nums[mid + 1]时,nums[mid]就是我们要找的数
3. Time & Space Complexity
Binary Search: 时间复杂度O(logn), 空间复杂度O(1)
Last updated