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;
    }
}

双指针思想!!!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值