Leetcode:Remove Duplicates from Sorted Array与Remove Element

来源:互联网 发布:建模 软件 数据 开源 编辑:程序博客网 时间:2024/04/30 08:35

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

设置一个变量size,初始化为0。遍历数组,如果A[i]不等于A[size],则为不重复的数,把A[i]的值赋给A[size],size加1,i继续遍历数组后面的数。最后,size+1的即为数组中不重复的数的个数。

实现代码如下:

public class Solution {    public int removeDuplicates(int[] A) {        if (A == null || A.length == 0) {            return 0;        }                int size = 0;        for (int i = 0; i < A.length; i++) {            if (A[i] != A[size]) {                A[++size] = A[i];            }        }        return size + 1;    }}


Remove Element:

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

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

设置变量i从头遍历数组,再设置一个变量end指向数组的末尾。如果遇到A[i]等于目标数字,把A[end]的值赋给A[i],在继续比较A[i]与目标数字,如果不相等,则遍历数组下一个元素,循环的条件为:i<=end.最终,数组的前end+1数,即为所求。

实现代码:

class Solution {public:    int removeElement(int A[], int n, int elem) {        int i=0;        int end=n-1;        while(i<=end)        {            if(A[i]==elem)            {                A[i]=A[end--];            }            else            i++;        }        return end+1;    }};


这两题难度都不大,把它们放在一起是因为可以总结一下遍历数组的方法,可以分别从两头遍历。还可以设置一个中间遍历,在遍历的过程中记录所需要的数值。

0 0