540. Single Element in a Sorted Array

来源:互联网 发布:sass编译是什么源码 编辑:程序博客网 时间:2024/06/08 11:32

1.题目

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:Input: [1,1,2,3,3,4,4,8,8]Output: 2Example 2:Input: [3,3,7,7,10,11,11]Output: 10Note: Your solution should run in O(log n) time and O(1) space.

2.分析
这道题其实难度真不大,做好边界处理就没有什么问题。一开始,我以为肯定会要求时间复杂度是O(n),但是是O(logn)- -,瞬间觉得这样简单多了,最直观的做法,比要求的的时间复杂度,空间复杂度都低。
3.解题
我的解法

class Solution {public int singleNonDuplicate(int[] nums) {    // 边界处理    if(nums==null||nums.length==0){        return 0;    }    if(nums.length==1){        return nums[0];    }    int len = nums.length;    int result = 0;    // 遍历一次O(n)的时间复杂度    for(int i=0;i<len;){        if(i+1<len&&nums[i+1]!=nums[i]){ // 一般情况下的递增            return nums[i];        }else if(i==len-1){ // 边界的处理            return nums[i];        }else{ // 递增条件            i = i+2;        }    }    return result;}}

别人的解法:

 public static int singleNonDuplicate(int[] nums) {    int start = 0, end = nums.length - 1;    while (start < end) {        // We want the first element of the middle pair,        // which should be at an even index if the left part is sorted.        // Example:        // Index: 0 1 2 3 4 5 6        // Array: 1 1 3 3 4 8 8        //            ^        int mid = (start + end) / 2;        if (mid % 2 == 1) mid--;        // We didn't find a pair. The single element must be on the left.        // (pipes mean start & end)        // Example: |0 1 1 3 3 6 6|        //               ^ ^        // Next:    |0 1 1|3 3 6 6        if (nums[mid] != nums[mid + 1]) end = mid;        // We found a pair. The single element must be on the right.        // Example: |1 1 3 3 5 6 6|        //               ^ ^        // Next:     1 1 3 3|5 6 6|        else start = mid + 2;    }    // 'start' should always be at the beginning of a pair.    // When 'start > end', start must be the single element.    return nums[start];}

4.总结
数组已经是排序数组,只需要进行数组遍历比较就能得出最后的结果,当然数组遍历递增的条件以及遍历的结束的边界条件都需要做好,这样最后就能得出正确的结果- -。别人的解法其实也是很好理解,首先根据题意需要O(logn)的时间复杂度,很容易想到的是二分查找的方法,然后根据题意,只有一个元素是出现一次,则数组长度肯定是奇数长度,然后若单独出现的元素在中间元素右侧,则中间元素肯定是出现两次的,若单独出现的元素出现在中间元素左侧,则中间肯定是不相等的,这样就将查找范围每次都缩减一般,如此一来,时间复杂度就大大缩小。

原创粉丝点击