代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素

  • 先完成第一题
    一开始就没看清题,以为是二分遍历
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        # split the array to two part
        # for each part, search each array element
        ## determine whether the element in the array is the same value with target
        if len(nums) % 2 == 1:
            index2_first = len(nums)//2 + 1
            if nums[len(nums)//2] == target:
                return len(nums)//2
        else:
            index2_first = len(nums)//2
        for i in range(len(nums)//2):
            index1 = i
            index2 = i + index2_first
            if nums[index1] != target and nums[index2] != target:
                continue
            if nums[index1] == target:
                return index1
            if nums[index2] == target:
                return index2
        return -1

看完题目后重新写:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        # find the middle element
        # determine whether the element in the array is the same value with target
        # if larger, go left, smaller, go right
        # send the new list to #1

        # middle = len(nums)//2
        left = 0
        right = len(nums)
        middle = len(nums)
        while left != right -1:
            middle = (left + right)//2
            # print(middle)
            if nums[middle] == target:
                return middle
            elif nums[middle] > target:
                right = middle
            else:
                left = middle
            print(left, right)
        if nums[0] == target:
            return 0
        else:
            return -1
posted @ 2024-02-22 00:53  HOJEST  阅读(20)  评论(0)    收藏  举报