leetcode33_Search in Rotated Sorted Array

橘子oly發表於2016-10-29

一.問題描述

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

二.演算法實現

    其實還是二分查詢的思想,只是在指標移動上多了很多需要判斷的條件。具體程式碼如下:

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # 還是二分查詢的思想,只是指標移動的條件有所改變
        len_nums = len(nums)
        left = 0
        right = len_nums-1
        mid = (left+right)/2
        while left<=right:
            if nums[mid] == target:
                return mid
            elif nums[left] == target:
                return left
            elif nums[right] ==target:
                return right
            elif nums[left]<nums[mid]:   # 說明左側list是遞增的
                if target>=nums[left] and target<=nums[mid]:
                    right = mid
                    mid = (left+mid)/2
                else:
                    left = mid
                    mid = (right+mid)/2
            elif target>=nums[mid] and target<=nums[right]:
                left = mid
                mid = (mid+right)/2
                if mid == left:
                    return -1
            else:
                right = mid
                mid = (mid+left)/2
                if mid == right:
                    return -1
        return -1

程式碼寫的很爛,好多ifelse判斷(因為想的時候沒考慮到所有情況吧,提交了好多次,一直在打補丁- -),最後一次提交的時候心驚膽戰的,怕時間打敗了0.001%的人,結果提交的時候發現打敗了92%的人,又驚又喜又嚇的- -,但是演算法在寫法上感覺還是不太美好,好多冗餘判斷的感覺,有待繼續提升。

    優化了一下,每次左右指標移動不是移動到mid處,而是mid加減1處。如下:

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        len_nums = len(nums)
        left = 0
        right = len_nums-1
        mid = (left+right)/2
        while left<=right:
            if nums[mid] == target:
                return mid
            elif nums[left] == target:
                return left
            elif nums[right] == target:
                return right
            elif nums[left]<nums[mid]:
                if target>=nums[left] and target<=nums[mid]:
                    right = mid-1
                    mid = (left+right)/2
                else:
                    left = mid+1
                    mid = (right+left)/2
            elif target>=nums[mid] and target<=nums[right]:
                left = mid+1
                mid = (left+right)/2
            else:
                right = mid-1
                mid = (right+left)/2
        return -1
提交了兩次,第一次是打敗了19%,嚇一跳,再提交一次就變成98%了,- -。。。


相關文章