求解有序数组中只出现一次的数字(Leetcode540)

2018-12-07  本文已影响0人  zhouwaiqiang

题目

解题思路

源代码实现

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int low = 0, high = nums.length-1;
        while (low < high) {
            int mid = low + (high - low)/2;
            //前后都不等那么nums[mid]就是要查找的数据
            if (nums[mid] != nums[mid-1] && nums[mid] != nums[mid+1]) return nums[mid];
            //mid表示偶数位置(从0开始)
            if (mid % 2 == 0) {
                if (nums[mid] == nums[mid+1]) low = mid;
                else high = mid;
            }
            else {
                if (nums[mid] == nums[mid-1]) low = mid+1;
                else high = mid-1;
            }
        }
        return nums[low];
    }
}
上一篇下一篇

猜你喜欢

热点阅读