码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]27. Remove Element删除元素

时间:2018-06-02 14:56:33      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:beyond   oca   mod   ret   with   ref   org   ++   代码   

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn‘t matter what you leave beyond the returned length.

 

题意:

给定某个值,要求删除数组中所有等于该值的元素。

 

思路:

    j 

以[3, 2, 2, 3], value = 3 为例

    i 

指针i遍历数组,遇到非value的值,送到指针j那里去

指针j从0开始,接收所有指针i送来的非value值

扫完一遍后

指针j所指的位置就是新“数组”的长度

 

代码:

1  public int removeElement(int[] nums, int target) {
2         int index = 0;
3         for (int i = 0; i < nums.length; ++i) {
4             if (nums[i] != target) {
5                 nums[index++] = nums[i];
6             }
7         }
8         return index;
9     }

 

[leetcode]27. Remove Element删除元素

标签:beyond   oca   mod   ret   with   ref   org   ++   代码   

原文地址:https://www.cnblogs.com/liuliu5151/p/9125368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!