zoukankan      html  css  js  c++  java
  • [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.”
  • 相关阅读:
    Intellij IDEA 配置Tomcat远程调试
    maven学习二(dependencies)
    maven学习一(HelloWorld工程)
    一致性hash在分布式系统中的应用
    理解TCP之Keepalive
    理解HTTP之keep-alive
    TCP/IP,http,socket,长连接,短连接
    图解 HTTP 协议
    PHP开发的一些趣事
    vue
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4576801.html
Copyright © 2011-2022 走看看