• [LeetCode] #33 Search in Rotated Sorted Array


    Suppose a sorted array 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).

    You are given a target value to search. If found in the array return its index, otherwise return -1.

    You may assume no duplicate exists in the array.

    本题利用二分算法的思想,判断target是在前半段还是后半段,再分开查找。时间:7ms。代码如下:

    class Solution {
    public:
        int search(vector<int>& nums, int f, int l, int target) {
            if (f>l)
                return -1;
            if (target == nums[f])
                return f;
            if (target == nums[l])
                return l;
            int mid = f + (l - f) / 2;
            if (target == nums[mid])
                return mid;
            if (nums[f] == nums[l] && nums[f] == nums[mid]){
                for (int i = f; i<l; i++){
                    if (nums[i] == target)
                        return i;
                }
                return -1;
            }
            if (nums[f] < target){
                if (nums[f]<nums[mid]&&target>nums[mid])
                    return search(nums, mid + 1, l, target);
                else
                    return search(nums, f, mid - 1, target);
            }
            else if(nums[l]>target){
                if (nums[mid]<nums[l] && target < nums[mid])
                    return search(nums, f, mid - 1, target);
                else
                    return search(nums, mid + 1, l, target);
            }
            return -1;
        }
        int search(vector<int>& nums, int target) {
            if (nums.size() == 0)
                return -1;
            return search(nums, 0, nums.size()-1, target);
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    扫目录过狗过waf方法
    https://www.webshell.cc/6274.html
    使用WireShark生成地理位置数据地图
    Aircrack-ng 扩展 : Marfil 分布式破解WIFI
    秒爆十万字典:奇葩技巧快速枚举“一句话后门”密码
    Python使用python-nmap模块实现端口扫描器
    Pandas之索引
    pandas之时间序列
    Pandas之分组
    Pandas学习笔记(一)
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4576801.html
Copyright © 2020-2023  润新知