1. 程式人生 > >leetcode:(540) Single Element in a Sorted Array(java)

leetcode:(540) Single Element in a Sorted Array(java)

題目:

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.

 題目描述:

   給定一個數組,陣列中只有一個數出現一次,其他的都出現兩次,找出這個出現一次的數。

解題思路:

     容易想到利用二分查詢,保證每次區間的兩段都是偶數,以便區間內數的個數為奇數,根據nums[mid]是否和nums[mid+1]相等,確定下一次的區間範圍。具體程式碼及解題思路如下:

package Leetcode_Github;

public class BinarySearch_SingleNonDuplicate_540_1113 {
    public int SingleNonDuplicate(int[] nums){
        int l = 0;//初始化l為陣列第一個元素
        int h = nums.length - 1;//初始化h為陣列末尾元素
        while (l < h) {
            int mid = l + (h - l) / 2;
            //如果mid是奇數,將mid減1,保證l、m、h均為偶數,區間有奇數個數
            if (mid % 2 == 1) {
                mid--;
            }
            //如果相等,說明出現一次的數在後半段
            if (nums[mid] == nums[mid + 1]) {
                l = mid + 2;
            }
            else
                h = mid;
        }
        return nums[l];
    }
}