[Leetcode]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 of nums being 2.

 

思路:这道题与 26.remove duplicates from sorted array思路一样。设置一个len=0;然后开始从0开始读数组里的数

如果这个数是满足条件的(!=val)则让把数赋在len位置上,并递增len的值。如果不满足条件即要移除这个数的话,

跳过什么都不做就好了。最后返回len的值。

 1 class Solution {
 2     public int removeElement(int[] nums, int val) {
 3         if (nums.length==0)
 4             return 0;
 5         int len = 0;
 6         for (int i=0;i<nums.length;i++){
 7             if (nums[i]!=val)
 8                 nums[len++] = nums[i];
 9         }
10         return len;
11     }
12 }

 

posted @ 2017-10-25 22:34  SkyMelody  阅读(121)  评论(0编辑  收藏  举报