This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
Solution1: fit for less tartget elements in array | |
public class Solution { | |
public int removeElement(int[] A, int elem) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
int len=A.length; | |
for (int i=0; i<len;){ | |
if (A[i]==elem){ | |
A[i]=A[--len]; | |
} | |
else{ | |
i++; | |
} | |
} | |
return len; | |
} | |
} | |
Solution 2: fit more elemetns in array | |
class Solution { | |
public int removeElement(int [] A, int elem){ | |
int newLen=0; | |
for (int i=0; i<A.length; i++){ | |
if (A[i]!=elem){ | |
A[newLen++]=A[i]; | |
} | |
} | |
return newLen; | |
} | |
} |
No comments:
Post a Comment