【LeetCode27】【Remove Element】

1.题目原文:

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.

2.题意解读:

做过第26道题目之后,这道题理解起来是比较容易的。仍旧是给定一个数组,把数组中所有与目标值(val)不相同的值移到前面。详细就不说了,没做过第26道题的话,可以看我的另一篇博文,链接:http://blog.csdn.net/csdnofheming/article/details/71302260

3.解法:

解法与第26道题的解法相似,仍旧是双指针方法解题,而且运行速度也很快,最快达到击败百分之90多的提交量。

代码如下:

public int removeElement(int[] nums, int val) {
        int count = 0;
        for(int num:nums){
            if(num!=val){
                nums[count++] = num; 
            }
        }
        return count;//因为每次"num!=val"成立时,给数组count位置赋值之后,总会给count+1,所以这里不用将count+1.
    }

4.涉及知识点:

设计知识点与第26道题相似,就不赘述了。

需要注意的一点:该方法返回count值,而不是count+1值,第一次提交时将”renturn count”误写成了”return count++”,幸运的是这个式子是先返回count,再将count+1,所以仍然是Accepted。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值