题目:
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.
题解:C++版:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0, j = nums.size() - 1;
while(i <= j) {
while(i <= j && nums[i] != val)
i++;
while(i <= j && nums[j] == val)
j--;
if(i <= j) {
nums[i] = nums[j];
i++;
j--;
}
}
return j + 1;
}
};
Java版:
public class Solution {
public int removeElement(int[] nums, int val) {
int i = 0, j = nums.length - 1;
while(i <= j) {
while(i <= j && nums[i] != val)
i++;
while(i <= j && nums[j] == val)
j--;
if(i <= j) {
nums[i] = nums[j];
i++;
j--;
}
}
return j + 1;
}
}
Python版:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 0:
return 0
i, j = 0, len(nums) - 1
while i <= j:
while i <= j and nums[i] != val:
i += 1
while j >= i and nums[j] == val:
j -= 1
if i <= j:
nums[i] = nums[j]
i += 1
j -= 1
return j + 1