[Leetcode]Remove Element配列要素の削除

1060 ワード

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. ダブルポインタ法複雑度時間O(N)空間O(1)構想は,1つのポインタで所与の数字を含まない配列境界を記録し,もう1つのポインタで現在遍歴している配列位置を記録する.与えられた数に等しくない数だけ、サブ配列の境界にコピーされます.コードpublic class Solution{public int removeElement(int[nums,int val]{int pos=0;for(int i=0;ipublic class Solution { public int removeElement(int[] nums, int val) { int size = nums.length, i = 0; while(i < size){ if(nums[i] == val){ swap(nums, i, size - 1); size--; } else { i++; } } return size; }
private void swap(int[] nums, int i, int j){
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp;
}

}