27. Remove Element
描述:
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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given 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,开始均指向数组第一个元素,j用于数组从头到尾按顺序扫描,如果元素nums[j] != val,则将其赋值给nums[i]。
最后返回i值即为新数组的长度。
2. 注意题目中“数组中元素的顺序可以改变”,由此可以想到用数组最后一个非val值来替换数组前面的等于val值的元素。也是设置两个
指针i,j,开始时i指向数组第一个元素,j指向数组最后一个元素。i从前向后扫描,j从后向前扫描:若nums[i] = val,就查看此时j指向
的元素是否等于val值,如果不等于val值则直接用nums[j]替换nums[i],如果等于val值则j继续向前扫描直至遇到nums[j] != val,然后用
nums[j]替换nums[i]。直至i值大于j值为止,结束循环,返回的i值即为新数组的长度。
这里提示一下,在审题过程中需要注意认真审题,虽然题目最后只要求返回新数组的长度,但是同时也要求直接在原数组上修改得到新
的数组,所以在考虑算法的时候不能只单纯追求得到正确的返回值,也需要得到正确的返回数组。
我的解决:
思路一:
class Solution {
public int removeElement(int[] nums, int val) {
int i=0;
for (int j = 0; j < nums.length; j ++){
if(nums[j] != val){
nums[i] = nums[j];
i++;
}
}
return i;
}
}
思路二:
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0, j = nums.length-1;
while(i <= j){
if(nums[i] == val){
if(nums[j] == val)
j--;
else{
nums[i] = nums[j];
j--;
i++;
}
}
else
i++;
}
return i;
}
}