码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode的medium题集合(C++实现)四

时间:2015-05-14 12:08:12      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   二分查找   

1 Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory.
从末尾向前寻找到元素a[i]第一次满足a[i]<a[i+1],再从末尾向前寻找到元素a[k],在k>i时 满足a[k]>a[i],如果找到则交换a[i]a[k] 并将a[i] 以后的元素倒置。

void nextPermutation(vector<int>& nums) {
        if (nums.size() < 2) return;
          int i, k;
          for (i = nums.size() - 2; i >= 0; --i) if (nums[i] < nums[i+1]) break;
          for (k = nums.size() - 1; k > i; --k) if (nums[i] < nums[k]) break;
          if (i >= 0) swap(nums[i], nums[k]);
           reverse(nums.begin() + i + 1, nums.end());
    }

2 Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm’s runtime complexity must be in the order of O(logn) .
If the target is not found in the array, return [-1, -1].
要保证时间复杂度为O(logn), 可以使用二分法,当因为存在多个相同的值,不能直接用二分法得到结果。我们可以使用两指针分别从左和右两个方向靠近目标值。

 int start=0, end=nums.size(),mid;
        vector<int> res(2,-1);
        if(nums[end-1]<target) return res;
        while(start<end)
        {
            mid=(start+end)/2;
            if(nums[mid]<target) 
               start=mid+1;
            else
               end=mid;  //保留可能存在目标值的元素
        }
        if(nums[start]!=target)
           return res;
        res[0]=start;
        end=nums.size();
        while(start<end)
        {
            mid=(start+end)/2;
            if(nums[mid]>target) 
               end=mid;
            else
               start=mid+1;  
        }
        res[1]=end-1;
        return res;
    }

3 Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array.
同样采用二分法解决,本题与上一题的不同之处在于while的循环条件为
start<=end, 而上一题为start<end,因为上一题为了保留可能存在目标值的元素使用了end=mid;,如果采用start<=end 会陷入死循环。而这里刚好当start>end 时 start会记录第一个大于目标值的下标。

int searchInsert(vector<int>& nums, int target) {
        int start=0, end=nums.size()-1, mid;
        while(start<=end)
        {
            mid=(start+end)/2;
            if(nums[mid]==target)
               return mid;
            else if(nums[mid]>target)
               end=mid-1;
            else
               start=mid+1;
        }
        return start;
    }

LeetCode的medium题集合(C++实现)四

标签:c++   leetcode   二分查找   

原文地址:http://blog.csdn.net/zhulong890816/article/details/45717931

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!