1. 程式人生 > >【Leetcode_總結】 540. 有序陣列中的單一元素

【Leetcode_總結】 540. 有序陣列中的單一元素

Q:

給定一個只包含整數的有序陣列,每個元素都會出現兩次,唯有一個數只會出現一次,找出這個數。

示例 1:

輸入: [1,1,2,3,3,4,4,8,8]
輸出: 2

示例 2:

輸入: [3,3,7,7,10,11,11]
輸出: 10

注意: 您的方案應該在 O(log n)時間複雜度和 O(1)空間複雜度中執行。

思路:有序 且執行時間為O(log n) 那麼就是使用二分查詢,程式碼如下:

class Solution:
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        low = 0
        high = len(nums) - 1
        while low < high:
            mid = (low + high)//2
            if mid%2 ==0:
                mid +=1
            if nums[mid] == nums[mid - 1]:
                low = mid + 1
            else:
                high = mid - 1
        return nums[low]

或者直接暴力。。。也能通過

class Solution:
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = {}
        for i in range(len(nums)):
            if nums[i] in dic:
                dic[nums[i]] += 1
            else:
                dic[nums[i]] = 1
        for k in dic:
            if dic[k] == 1:
                return k