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

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;
    }
时间: 2024-08-03 17:25:55

LeetCode的medium题集合(C++实现)四的相关文章

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

1 Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.Here, we will use the integers 0, 1, and 2 to represent the color red,

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

1 Subsets Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,3], a solution is: [ [3], [1],

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

1 Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index. 利用两指针法

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

1 Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked

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

1 Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. 可以采用递归的方法解决这个问题,当找到一组数之和

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

1 Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative. 该题实际就是利用字符串来解决大数的乘法问题.为了计算方便先将两组数翻转,将字符串转化为整数利用两个循环逐位相乘,将结果保存.然后逐位解决进位问题. s

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

1 4Sum Given an array S of n integers, are there elements a,b,c,d in S such that a+b+c+d=target ? Find all unique quadruplets in the array which gives the sum of target. 利用公式a+b=target?c?d 可以将四数和转化为两数和的问题. vector<vector<int>> fourSum(vector<

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

1 Pow(x, n) 该题采用二分法进行递归 double myPow(double x, int n) { if(n==0) return 1; if(n<0) { n=(-n); x=1/x; } double res=myPow(x,n/2); if(n%2==0) { return res*res; } else { return res*res*x; } } 2 Maximum Subarray Find the contiguous subarray within an array

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

1 Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations.Given n and k, return the kth permutation sequence. 使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制.下面采用数学法: 在n!个排列中,第一位元素相同的排列总是有(n?1)!个,如果p=k/(n?1)!,那么排列的第一位元素