/**
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.
题目大意:给一个数组一个数字,从数组里删掉这个数字,返回剩下的数组长度
**/
public class Solution {
public int removeElement(int[] A, int elem) {
return solve1(A, elem);
//return solve2(A, elem); //错误答案
}
//====================== solve1 ==========================
//O(n)
//双指针,index记录新指针的长度,i则一直遍历,同时将数组元素前移,最后index指向的位置就是新数组的长度
//
private int solve1(int[] A, int elem) {
int index = -1;
int i= -1;
for(i=0, index=0; i<A.length; i++)
if(A[i] != elem)
A[index++] = A[i];
return index;
}
//====================== solve2 ==========================
//这个是错误答案,在这一题里,原本的那个数组是必须要修改的,不能纯粹是算个数
private int solve2(int[] A, int elem){
int result = 0;
for(int a : A)
if(a != elem)
result++;
return result;
}
}
LeetCode:Remove Element
最新推荐文章于 2019-11-06 10:59:57 发布