Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
투 포인트로 문제를 풀겠다.
int l = nums.length - 1
for(f = 0; f <= l; f++)
while(f <= l && nums[l] == val)
l--
if(f < l && nums[f] == val)
temp = nums[l]
nums[l] = nums[f]
nums[f] = temp
return l + 1
int l = nums.length - 1;
for (int f = 0; f <= l; f++) {
while (f <= l && nums[l] == val) {
l--;
}
if (f < l && nums[f] == val) {
int temp = nums[l];
nums[l] = nums[f];
nums[f] = temp;
}
}
return l + 1;
int f = 0;
int l = nums.length - 1;
int t;
while(f < nums.length && l > 0 && f < l){
if(nums[f] == val && nums[l] != val){
t = nums[f];
nums[f] = nums[l];
nums[l] = t;
}
if(nums[f] != val)
f++;
if(nums[l] == val)
l--;
}
int i = 0;
for(; i < nums.length; i++){
if(nums[i] == val)
break;
}
return i;
예전에 비해 코드를 더 깔끔하게 작성했지만, 이 코드에는 못 미친다
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[index] = nums[i];
index++;
}
}
return index;