Algorithm leetcode|81. Searching rotated sorted array II (rust punch)



81. Searching a rotated sorted array II:

Given that there exists an array of integers in non-descending order nums, the values ​​in the array need not be distinct from each other.

Before being passed to the function, a rotation is performed on numssome previously unknown index k( ) , so that the array becomes (the index starts counting from 0 ). For example, the index may become after rotation .0 <= k < nums.length[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]][0,1,2,4,4,4,5,6,6,7]5[4,5,6,6,7,0,1,2,4,4]

Given your rotated array numsand an integer target, please write a function to determine whether the given target value exists in the array. Returns if numsthis target value exists in , otherwise .targettruefalse

You have to reduce the number of steps as much as possible.

Example 1:

输入:
	
	nums = [2,5,6,0,0,1,2], target = 0
	
输出:
	
	true

Example 2:

输入:
	
	nums = [2,5,6,0,0,1,2], target = 3
	
输出:
	
	false

hint:

  • 1 <= nums.length <= 5000
  • -104 <= nums[i] <= 104
  • The question data guarantees that nums is rotated on a pre-unknown index.
  • -104 <= target <= 104

Advanced:

  • This is an extended question of searching a rotated sorted array . In this question, numsmay contain duplicate elements.
  • Will this affect the time complexity of the program? What impact will it have and why?

analyze:

  • Facing this algorithm question, the second master once again fell into deep thought.
  • If there is no rotation, then definitely use binary search. Binary search can exclude half of the data in each loop traversal, which is very efficient.
  • To use binary search, the array must be ordered, but the array has been rotated, so it is not completely ordered, but it is not completely impossible.
  • The general dichotomy is to compare the middle elements each time, and then determine whether the elements are equal. If they are not equal, check whether the elements should be in the left half or the right half, thus excluding half of the elements, and then continue to repeat this logic in the other part. .
  • We can use a deformed binary search. It can be imagined that after the ordered array is rotated, it is divided into two parts. One part must be ordered, and the other part must be partially ordered, but the head must not be smaller than the tail, so we can judge first Which part is in order, and then see whether the target number is in the ordered part, to decide whether to change the left boundary or the right boundary, so that the efficiency of binary search can be achieved.
  • Since duplicate elements are allowed in the array, during a certain search, the middle element, head and tail elements may be the same. At this time, there is no way to judge which half is in order, and half cannot be directly excluded. elements, but we can exclude the head and tail elements.

answer:

rust:

impl Solution {
    
    
    pub fn search(nums: Vec<i32>, target: i32) -> bool {
    
    
        let n = nums.len();
        if n == 0 {
    
    
            return false;
        }
        if n == 1 {
    
    
            return nums[0] == target;
        }
        let (mut l, mut r) = (0, n - 1);
        while l <= r {
    
    
            let mid = (l + r) >> 1;
            if nums[mid] == target {
    
    
                return true;
            }
            if nums[l] == nums[mid] && nums[mid] == nums[r] {
    
    
                if r == 0 {
    
    
                    // 防止r溢出到非常大
                    return false;
                }
                l += 1;
                r -= 1;
            } else if nums[l] <= nums[mid] {
    
    
                if nums[l] <= target && target < nums[mid] {
    
    
                    r = mid - 1;
                } else {
    
    
                    l = mid + 1;
                }
            } else {
    
    
                if nums[mid] < target && target <= nums[n - 1] {
    
    
                    l = mid + 1;
                } else {
    
    
                    r = mid - 1;
                }
            }
        }
        return false;
    }
}

go:

func search(nums []int, target int) bool {
    
    
    n := len(nums)
	if n == 0 {
    
    
		return false
	}
	if n == 1 {
    
    
		return nums[0] == target
	}
	l, r := 0, n-1
	for l <= r {
    
    
		mid := (l + r) >> 1
		if nums[mid] == target {
    
    
			return true
		}
		if nums[l] == nums[mid] && nums[mid] == nums[r] {
    
    
			l++
			r--
		} else if nums[l] <= nums[mid] {
    
    
			if nums[l] <= target && target < nums[mid] {
    
    
				r = mid - 1
			} else {
    
    
				l = mid + 1
			}
		} else {
    
    
			if nums[mid] < target && target <= nums[n-1] {
    
    
				l = mid + 1
			} else {
    
    
				r = mid - 1
			}
		}
	}
	return false
}

c++:

class Solution {
    
    
public:
    bool search(vector<int>& nums, int target) {
    
    
        const int n = nums.size();
        if (n == 0) {
    
    
            return false;
        }
        if (n == 1) {
    
    
            return nums[0] == target;
        }
        int l = 0, r = n - 1;
        while (l <= r) {
    
    
            int mid = (l + r) >> 1;
            if (nums[mid] == target) {
    
    
                return true;
            }
            if (nums[l] == nums[mid] && nums[mid] == nums[r]) {
    
    
                ++l;
                --r;
            } else if (nums[l] <= nums[mid]) {
    
    
                if (nums[l] <= target && target < nums[mid]) {
    
    
                    r = mid - 1;
                } else {
    
    
                    l = mid + 1;
                }
            } else {
    
    
                if (nums[mid] < target && target <= nums[n - 1]) {
    
    
                    l = mid + 1;
                } else {
    
    
                    r = mid - 1;
                }
            }
        }
        return false;
    }
};

python:

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        if not nums:
            return False

        n = len(nums)
        if n == 1:
            return nums[0] == target

        l, r = 0, n - 1
        while l <= r:
            mid = (l + r) >> 1
            if nums[mid] == target:
                return True
            if nums[l] == nums[mid] and nums[mid] == nums[r]:
                l += 1
                r -= 1
            elif nums[l] <= nums[mid]:
                if nums[l] <= target < nums[mid]:
                    r = mid - 1
                else:
                    l = mid + 1
            else:
                if nums[mid] < target <= nums[n - 1]:
                    l = mid + 1
                else:
                    r = mid - 1

        return False


java:

class Solution {
    
    
    public boolean search(int[] nums, int target) {
    
    
        final int n = nums.length;
        if (n == 0) {
    
    
            return false;
        }
        if (n == 1) {
    
    
            return nums[0] == target;
        }
        int l = 0, r = n - 1;
        while (l <= r) {
    
    
            int mid = (l + r) / 2;
            if (nums[mid] == target) {
    
    
                return true;
            }
            if (nums[l] == nums[mid] && nums[mid] == nums[r]) {
    
    
                ++l;
                --r;
            } else if (nums[l] <= nums[mid]) {
    
    
                if (nums[l] <= target && target < nums[mid]) {
    
    
                    r = mid - 1;
                } else {
    
    
                    l = mid + 1;
                }
            } else {
    
    
                if (nums[mid] < target && target <= nums[n - 1]) {
    
    
                    l = mid + 1;
                } else {
    
    
                    r = mid - 1;
                }
            }
        }
        return false;
    }
}

Thank you very much for reading this article~
Welcome to [Like] [Collect] [Comment] Three in a row ~ It
is not difficult to give up, but it must be cool to persist ~
I hope we can all make a little progress every day ~
This article is written by the second-in-command white hat: https://le-yi.blog.csdn.net/Original blog~


Guess you like

Origin blog.csdn.net/leyi520/article/details/132888132