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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
JAVA
方法一
与26题相似,也是要返回有效的数组长度并让全部有效数字都在数字的前端。
用两个指针从数组两端向中间扫描即可。P1从左向右扫描,P2从右向左扫描,当P1指向的值不等于val时,result+1并且P1右移,当等于val时,开始移动P2指针,找到第一个不等于val的数与P1交换。
效率依然排在后1/3。。。
public class Solution {
public int removeElement(int[] nums, int val) {
int result = 0;
int p1 = 0;
int p2 = nums.length - 1;
int temp;
while(p1 <= p2){
while(p1 <= p2){
if(nums[p1] == val){
break;
}else{
++result;
++p1;
}
}
while(p1 <= p2){
if(nums[p2] != val){
temp = nums[p1];
nums[p1] = nums[p2];
nums[p2] = temp;
++p1;
++result;
--p2;
break;
}else{
--p2;
}
}
}
return result;
}
}
方法二
看了下效率高的算法,果然简单了很多,虽然时间复杂度同样是 O(N) ,但是代码和思想的复杂程度降了很多,非常简单的思路,效率却很高
public int removeElement(int[] nums, int val) {
int news = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != val){
nums[news] = nums[i];
news ++;
}
}
return news;
}