1. 程式人生 > >Remove Element (java版)

Remove Element (java版)

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.

給定一個數組和一個值,刪除該值的所有例項,並返回新的長度。

不要為另一個數組分配額外的空間,您必須使用常量記憶體來進行此操作。

元素的順序可以改變。

思路如下:

1、使用遊標i,j遍歷陣列,如果遇到和val相等的元素,用j記錄位置,並遞增i,直到下一個和val不相等的元素出現。

2、將此時i對應的值複製到j的位置;再增加j;直到遍歷結束

程式碼如下:

public class 
RemoveElement { public static void main(String[] args) { int[] nums = {2}; int val=3; RemoveElement r=new RemoveElement(); System.out.println(r.removeElement(nums,val)); } public int removeElement(int[] nums, int val) { int j=0; for (int
i = 0; i <nums.length ; i++) { if(nums[i]==val){ continue; } nums[j]=nums[i]; j++; } return j; } }