[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 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.

Example:

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

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

思路:

 1 public class Solution27 {
 2     public int removeElement(int[] nums, int val) {
 3         int index=0;
 4         for(int i = 0;i < nums.length;i++){
 5             if(nums[i] != val){
 6                 nums[index++] = nums[i];
 7             }
 8         }
 9         return index;
10     }
11     public static void main(String[] args) {
12         // TODO Auto-generated method stub
13         int[] nums = {3,2,2,3};
14         int val = 3;
15         Solution27 solution27 = new Solution27();
16         System.out.println(solution27.removeElement(nums, val));
17     }
18 
19 }
原文地址:https://www.cnblogs.com/zlz099/p/8144926.html