Search in Rotated Sorted Array II

LeetCode Q 81 - Search in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.

Solution

For this question, we need to know the worst case is
there is a 0 in the array like [1, 1, 1, 1, 1,…, 1].
In this case, we cannot use binary search. The time complexity of the algorithm will become O(n).
Therefore, we can just use a for loop to solve it.
This question is testing whether we can think of the worst case.

Code:

public booelan search(int[] nums, int target) {
	if (nums == null || nums.length == 0) return false;
	for (int num: nums) {
		if (num == target) return true;
	}
	return false;
}

   Reprint policy


《Search in Rotated Sorted Array II》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC