Array

26. Remove Duplicates from Sorted Array


Given a sorted array, 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 in place with constant memory.

For example,
Given input array 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 new length.

删除有序数组中的重复元素。倒着遍历并删除重复元素可以减少移动元素开销。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int len=nums.size();
        for(int i=len-1;i>0;i--){
            if(nums[i]==nums[i-1]){
                nums.erase(nums.begin()+i);
            }
        }
        return nums.size();
    }
};


27. Remove Element


Given an array and a value, 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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3]val = 3

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

移除元素,如果不想改变元素顺序,可以考虑26题倒着遍历的方法;也可以采用双指针从两端遍历,但是会改变元素的顺序。

倒着遍历:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        for(int i=nums.size()-1;i>=0;i--){
            if(nums[i]==val){
                nums.erase(nums.begin()+i);
            }
        }
        return nums.size();
    }
};
双指针:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int begin=0;
        int end=nums.size()-1;
        while(begin<=end){
            if(nums[begin]==val){
                int temp=nums[begin];
                nums[begin]=nums[end];
                nums[end]=temp;
            }else{
                begin++;
            }
            while(nums[end]==val){
                end--;
            }
        }
        return end+1;
    }
};

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, do not allocate 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

求下一个排列,思路类似于字典序。先倒着遍历找到第一个升序序列对,标记前一个数字的位置。再次倒着遍历,将第一个大于标记数字的数字与标记数字作交换。最后将标记位置之后的所有数字逆序。

class Solution {
public:
    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;
        }
        if(i<0){
            reverse(nums.begin(),nums.end());
            return;
        }else{
            for(k=nums.size()-1;k>i;k--){
                if(nums[i]<nums[k]){
                    swap(nums[i],nums[k]);
                    reverse(nums.begin()+i+1,nums.end());
                    return;
                }
            }
        } 
        return;
    }
};

41. First Missing Positive


Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

在无序的整数数组中找到第一个缺失的正整数。我们假设不存在缺失的正整数,即从nums[0]到nums[n-1]中存储的正好是1到n,那么将数字按升序排列后,nums[i]-1=i,即nums[0]中存储1,nums[1]中存储2...于是我们对nums遍历,将nums[i]交换到它应该在的位置,即nums[nums[i]-1]的位置,不断的交换直到当前nums[i]<=0或nums[i]>n。这样一轮遍历之后,所有未缺失的正整数都回到了它们应该在的位置上,此时再从头开始遍历,第一个满足nums[i]!=i+1的位置所应该存在的数字,即是缺失的正整数。

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n=nums.size();
        for(int i=0;i<n;++i)
            while(nums[i]>0 && nums[i]<=n && nums[nums[i]-1]!=nums[i])
                swap(nums[i],nums[nums[i]-1]);
        for(int i=0;i<n;++i)
            if(nums[i]!=i+1)
                return i+1;
        return n+1;
    }
};

48. Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

将二维矩阵顺时针旋转90°。数学问题,思路是先沿水平中线对称交换,再沿矩阵主对角线两两交换元素。

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        reverse(matrix.begin(),matrix.end());
        for(int i=0;i<matrix.size();++i){
            for(int j=i+1;j<matrix[i].size();++j)
                swap(matrix[i][j],matrix[j][i]);
        }
    }
};

54. Spiral Matrix


Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

对矩阵螺旋取数。设置好上下左右四个边界,以及循环跳出条件,按照顺序取数即可。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty()) return {};
        int m=matrix.size();
        int n=matrix[0].size();
        vector<int> result;
        int l=0,r=n-1,u=0,d=m-1,k=0;
        while(true){
            for(int col=l;col<=r;col++) result.push_back(matrix[u][col]);
            if(++u>d) break;
            for(int row=u;row<=d;row++) result.push_back(matrix[row][r]);
            if(--r<l) break;
            for(int col=r;col>=l;col--) result.push_back(matrix[d][col]);
            if(--d<u) break;
            for(int row=d;row>=u;row--) result.push_back(matrix[row][l]);
            if(++l>r) break;
        }
        return result;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值