[LeetCode] 540. Single Element in a Sorted Array

來源:互聯網
上載者:User

標籤:this   span   個數   cep   bsp   duplicate   dup   public   color   

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: 2

 

Example 2:

Input: [3,3,7,7,10,11,11]Output: 10

 

Note: Your solution should run in O(log n) time and O(1) space.

 

題意:給一個排好序的數組,其中只有一個數字出現了1次,其餘都出現了2次

二分的思想,這次判斷的是奇偶,舉個例子:

1) 1  1  2  3  3  4  4  8  8

二分先找中間,我們指向了nums[4] = =3 的位置,判斷它的左右,找到第一個相同的數,什麼意思呢,

我們假設現在數組是這樣的

2)1  1  2  2  3  4  4  8  8           3的左和右都和它不等,那麼3是我們要找的

假設數組現在是這樣的

3)1  1  2  2  3  3  4  8  8           同1中做一下比較,1中第一個3的位置是3,從這個點起,左右兩邊(左邊包括這個位置)哪邊是奇數,那麼那個只有1次的數字就在那邊

這裡注意一下,最左邊和最右邊有越界的情況,提前處理一下

class Solution {    public int singleNonDuplicate(int[] nums) {        if (nums.length == 1)            return nums[0];        if (nums[0] != nums[1])            return nums[0];        int r = nums.length - 1;        int l = 0;        if (nums[r] != nums[r - 1])            return nums[r];        while (r - l > 5) {            int mid = (r + l) / 2;            if (nums[mid-1] != nums[mid] && nums[mid] != nums[mid+1])                return nums[mid];            if (nums[mid + 1] == nums[mid])                mid ++;            if ((mid - l + 1)%2 == 0)                l = mid + 1;            else                r = mid;        }        if (l == 0)            l++;        if (r == nums.length - 1)            r--;        for (int i = l; i <= r; i++) {            if (nums[i - 1] != nums[i] && nums[i] != nums[i + 1])                return nums[i];        }        return 0;    }}

 

[LeetCode] 540. Single Element in a Sorted Array

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.