【LeetCode】C# 81、Search in Rotated Sorted Array II

Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order 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).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

在翻转过的包含重复数的数组中查找元素。

思路一:直接遍历。也能AC……

public class Solution {
    public bool Search(int[] nums, int target) {
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] == target)
                return true;
        }
        return false;
    }
}

思路二:
因为重复的原因,可能左右两端数值相同,使我们失去二分挑边的功能。解决办法是对边缘移动一步,直到边缘和中间不在相等或者相遇。所以最坏情况(比如全部都是一个元素,或者只有一个元素不同于其他元素,而他就在最后一个)就会出现每次移动一步,总共是n步,算法的时间复杂度变成O(n)。
思路参考:http://blog.csdn.net/linhuanmars/article/details/20588511


public bool search(int[] nums, int target) {
    if(nums==null || nums.Length==0)
        return false;
    int l = 0;
    int r = nums.Length-1;
    while(l<=r)
    {
        int m = (l+r)/2;
        if(nums[m]==target)
            return true;
        if(nums[m]>nums[l])
        {
            if(nums[m]>target && nums[l]<=target)
            {
                r = m-1;
            }
            else
            {
                l = m+1;
            }
        }
        else if(nums[m]<nums[l])
        {
            if(nums[m]<target && nums[r]>=target)
            {
                l = m+1;
            }
            else
            {
                r = m-1;
            }                
        }
        else
        {
            l++;
        }
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值