Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

540. Single Element in a Sorted Array #156

Open
Tcdian opened this issue May 12, 2020 · 1 comment
Open

540. Single Element in a Sorted Array #156

Tcdian opened this issue May 12, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 12, 2020

540. Single Element in a Sorted Array

给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。

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

  • 您的方案应该在 O(log n) 时间复杂度和 O(1) 空间复杂度中运行。
@Tcdian
Copy link
Owner Author

Tcdian commented May 12, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNonDuplicate = function(nums) {
    let left = 0;
    let right = nums.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === nums[mid - 1]) {
            if ((right - mid) % 2 === 1) {
                left = mid + 1;
            } else {
                right = mid - 2;
            }
        } else if (nums[mid] === nums[mid + 1]) {
            if ((mid - left) % 2 === 1) {
                right = mid - 1;
            } else {
                left = mid + 2;
            }
        } else {
            return nums[mid];
        }
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant