【LeetCode】27. Remove Element

来源:互联网 发布:悍将传世源码 编辑:程序博客网 时间:2024/06/05 11:12

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 ofnums being 2.


给定一个数组和一个值,删除该值的所有实例并返回新的长度。不要为另一个数组分配额外的空间,您必须在内存不变的情况下这样做。元素的顺序可以被改变。你在新的长度之外留下什么并不重要。


这道题与26题很相似,做了26题,明白了参考答案的解法后就会觉得这道题很简单。用i和j两个指针,同样的,i所指过的地方都是不与val相等的,j是用来找那个不相等的数。

26题:http://blog.csdn.net/ontheroad_/article/details/77916904

class Solution {    public int removeElement(int[] nums, int val) {        int i=0;        for(int j=0;j<nums.length;j++){            if(nums[j]!=val){                nums[i]=nums[j];                i++;            }        }        return i;    }}


参考答案还给出了另一种解法。如果nums[i]与val相等,就把后面的数赋值给nums[i],同时n--,继续当前的nums[i]。如果不相等,i就指向下一个


public int removeElement(int[] nums, int val) {    int i = 0;    int n = nums.length;    while (i < n) {        if (nums[i] == val) {            nums[i] = nums[n - 1];            // reduce array size by one            n--;        } else {            i++;        }    }    return n;}










原创粉丝点击