Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
時(shí)間 O(N) 空間 O(1)
用一個(gè)指針記錄不含給定數(shù)字的數(shù)組邊界,另一個(gè)指針記錄當(dāng)前遍歷到的數(shù)組位置。只有不等于給定數(shù)字的數(shù),才會(huì)被拷貝到子數(shù)組的邊界上。
public class Solution { public int removeElement(int[] nums, int val) { int pos = 0; for(int i = 0; i < nums.length; i++){ // 只拷貝非給定數(shù)字的元素 if(nums[i] != val){ nums[pos] = nums[i];pos++;}} return pos;}}
聯(lián)系客服