Leetcode解题报告——540. Single Element in a Sorted Array

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中找出只出现过一次的数,而且这个数组很特殊,所有数都出现过2次,只有1个数出现了一次。这题本身并不难,难的是题目限定了复杂度,这样的话遍历显然是不符合要求,O(log n)的复杂度提示了我们要用分治的方法,每次用下标 i 将一个数组截成两半,左右两半不可能同时存在只出现一次的数,通过比较当前数组的长度和 nums[i] 和 nums[i-1]的关系,找出符合条件的那一半作为参数递归调用自用的函数即可。为了保证 nums[i - 1]有效,我们对 nums长度等于1的情况做了特殊处理。

代码如下:

class Solution(object):
    def singleNonDuplicate(self, nums):
        print(nums)
        if len(nums) == 1:
            return nums[0]
        if len(nums) == 3:
            if(nums[1] == nums[0]):
                return nums[2]
            else:
                return nums[0]

        mid = len(nums) // 2
        print(mid)
        if mid % 2 == 0:
            if nums[mid] == nums[mid - 1]:
                return self.singleNonDuplicate(nums[0:mid - 1])
            else:
                return self.singleNonDuplicate(nums[mid:])
        else:
            if nums[mid] == nums[mid - 1]:
                return self.singleNonDuplicate(nums[mid + 1:])
            else:
                return self.singleNonDuplicate(nums[0:mid ])

猜你喜欢

转载自blog.csdn.net/weixin_38224302/article/details/80222243