Follow up for Search in Rotated Sorted Array:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Example
Given [1, 1, 0, 1, 1, 1] and target = 0, return true.
Given [1, 1, 1, 1, 1, 1] and target = 0, return false.
思路
因为有duplicates,所以没法用二分法做。因为你在碰到一个数的时候没法知道到底是往左还是往右搜索。只能for循环过一遍。
Code
public class Solution { /** * param A : an integer ratated sorted array and duplicates are allowed * param target : an integer to be search * return : a boolean */ public boolean search(int[] A, int target) { // write your code here for (int i = 0; i < A.length; i++) { if (A[i] == target) { return true; } } return false; } }