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.

给定一个数组和一个值,删除该值的所有实例并返回新的长度。

不要为另一个数组分配额外的空间,您必须在内存不变的情况下这样做。
元素的顺序可以被改变。你在新的长度之外留下什么并不重要。
例子:
给定输入数组nums=3,2,2,3,val=3
你的函数应该返回长度=2,而nums的前两个元素是2。

解题过程:

本人在求解时,将问题考虑的太复杂了,我想的是相同的值要跳过,找到不同的值将其覆盖掉。实际上是没有必要考虑相同的值。

因为在求解时,你也只需要将不同的值保留下来即可。因此,只需要遍历整个数组,当数组中的值与给定的值相同时,跳过不作处理。

不同时,将其保存下来,形成新的数组即可。

代码如下:

public class Solution 
{
    public int removeElement(int[] nums, int val) 
    {
    
        int j=0;
        int last=0;
        int sub=0;
        while(j<nums.length)
        {
            if(nums[j]!=val)
            {
                nums[last]=nums[j];//实际上last就是一个从头到尾的游动指针,因为不能开辟空间,故通过这一种方式形成新的数组。
                last++;  //计数器
            }
            j++; 
        }
        return last;
    }
}

大神做法:

(其实代码要比我写的多,不过运行效率要快好多)

主要是运用了交换的思想。

public class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums == null || nums.length == 0)
            return 0;
        if(nums.length == 1)
            return nums[0] == val ? 0 : 1;
        int front = 0;
        int end = nums.length - 1;
        int counter = 0;
        while(front < end){
            while(end >= 0 && nums[end] == val){
                counter++;
                end--;
            }
            while(front <= nums.length-1 && nums[front] != val){
                front++;
            }
            if(front < end){
                swap(nums, front, end);
            }
        }
        return nums.length - counter;
    }
    
    private void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

双指针思想!!!

猜你喜欢

转载自blog.csdn.net/qq_36251958/article/details/76165900