Array - 26. 27. 31不会 33. 34. 35. 39. 40.

26. Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

提示:The answer is amazing.如果不用range for 就要多加一个int count

答案:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = !nums.empty();
        for (int n : nums)
            if (n != nums[i-1])
                nums[i++] = n;
        return i;
   }
};

27. Remove Element

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

提示:利用条件语句可以减少代码行,题目中说明数组顺序可以打乱,让其等于最后的元素可以减少移动操作。

答案:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i = 0, n = nums.size();
        while (i < n) (nums[i] == val)? nums[i] = nums[--n] : i++; 
        return n;
    }
};
31 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 and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

提示:

答案:

33. Search in Rotated Sorted Array

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]).

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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

提示:二分查找  分两种情况   mid < end  mid > end

答案: 

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.empty())  return -1; 
        int start = 0, end = nums.size() - 1;
        while(start < end){
            int mid = (start + end)/2;
            if(nums[mid] < nums[end]){// eg. 5,6,1,2,3,4
                if(target > nums[mid] && target <= nums[end]){ 
                    start = mid + 1;
                }else{
                    end = mid;
                }
            }else{// eg. 3,4,5,6,1,2
                if(target > nums[mid] || target <= nums[end]){
                    start = mid + 1;
                }else{
                     end = mid;
                }   
            }
        }
        if(target != nums[start])  return -1;
        return start;
    }
};
34. Search for a Range

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

提示:方法一:二分查找  右边界 通过 mid = (l+r +1)/2获得

           方法二:二分查找找到左边界,因为递增排序,所以右边界为target+1的左边界-1。注意target+1不存在时                              也要让l=mid +1。

答案:

class Solution {
private: 
    int left(vector<int>& nums, int target){
        int l = 0, r = nums.size();
        while(l < r){
            int mid = (l + r) / 2;
            if(nums[mid] < target)  l = mid + 1;
            else r = mid; 
        }
        return l;
    }
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1, -1};
        int l = left(nums, target);
        if(l == nums.size() || target != nums[l])  return {-1, -1};
        else return {l, left(nums, target + 1) - 1};
    }
};

利用STL:

vector<int> searchRange(vector<int>& nums, int target) {
    auto bounds = equal_range(nums.begin(), nums.end(), target);
    if (bounds.first == bounds.second)
        return {-1, -1};
    return {bounds.first - nums.begin(), bounds.second - nums.begin() - 1};
}


vector<int> searchRange(vector<int>& nums, int target) {
    int lo = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    if (lo == nums.size() || nums[lo] != target)
        return {-1, -1};
    int hi = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1;
    return {lo, hi};
}
35. 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.

Example 1:

Input: [1,3,5,6], 5

Output: 2

提示:二分查找 

答案:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int start = 0, end = nums.size();
        while(start < end){
            int mid = (start + end) / 2;
            if(nums[mid] >= target) end = mid;
            else start = mid + 1;
        }
        return start;
    }
};
39. Combination Sum

Given a set of candidate numbers (candidates(without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]

]

提示:sort 回溯法

答案:

class Solution {
private:
   void backtracking(vector<int>& candidates, int target, vector<vector<int>>& result, vector<int>& combination, int begin){
        if(!target){
            result.push_back(combination);
            return;
        }
        for(int i = begin; i < candidates.size() && target >= candidates[i]; ++i){
            combination.push_back(candidates[i]);
            backtracking(candidates, target - candidates[i], result, combination, i);
            combination.pop_back();
        }
        return;
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> result;
        vector<int> combination;
        backtracking(candidates, target, result, combination, 0);
        return result;
    }
};
40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]

]

提示:回溯法 

答案:

class Solution {
private:
   void backtracking(vector<int>& candidates, int target, vector<vector<int>>& result, vector<int>& combination, int begin){
        if(!target){
            result.push_back(combination);
            return;
        }
        for(int i = begin; i < candidates.size() && target >= candidates[i]; ++i){
            if (i == begin || candidates[i] != candidates[i - 1]) {
                combination.push_back(candidates[i]);
                backtracking(candidates, target - candidates[i], result, combination, i + 1);
                combination.pop_back();
            }
        }
        return;
    }
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> result;
        vector<int> combination;
        backtracking(candidates, target, result, combination, 0);
        return result;
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值