Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
思路:此題比較簡單,大意是將數組中重復點刪除,然後返回新數組的長度。數組中前n個數就是新的數組。唯一難點是不能用額外空間。
詳細代碼如下:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length <= 1){
return nums.length;
}
int len = 1;//新的長度,至少為1,以下循環從i=1開始
for(int i = 1; i < nums.length; i++){
if(nums[i] != nums[i-1]){//不等於前一個元素,長度+1
nums[len++] = nums[i];//將新的元素裝到前len個
}
}
return len;
}
}