LeetCode-Single Element in a Sorted Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83790731

一、Description

题目描述:在一个有序数组中找出只出现一次的数字,要求时间复杂度为O(log n) 。

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

二、Analyzation

方法一:

如果没有时间复杂度的要求,可以考虑用异或的思路,所有出现两次的数字通过异或相互抵消,剩下的数字就是只出现一次的。

见code1。

方法二:

二分法:令index为Single Element在数组中的位置。l = 0,h = nums.length - 1,m = l + (h - l) / 2。通过观察我们可以发现,如果m为偶数,并且nums[m] == nums[m + 1],那么index所在的位置为[m + 2, h],此时令 l = m + 2;如果 nums[m] != nums[m + 1],那么 index 所在的数组位置为 [l, m],此时令 h = m。

因为 h 的赋值表达式为 h = m,那么循环条件也就只能使用 l < h 这种形式。

见code2。


三、Accepted code

code1:

class Solution {
    public int singleNonDuplicate(int[] nums) {
        if (null == nums || 0 == nums.length) {
            return -1;
        }
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            result ^= nums[i];
        }
        return result;
    }
}

code2:

class Solution {
    public int singleNonDuplicate(int[] nums) {
        if (null == nums || 0 == nums.length) {
            return -1;
        }
        int l = 0, h = nums.length - 1;
        while (l < h) {
            int m = l + (h - l) / 2;
            if (m % 2 == 1) {
                m--;
            }
            if (nums[m] == nums[m + 1]) {
                l = m + 2;
            } else {
                h = m;
            }
        }
        return nums[l];
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83790731