国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Remove Duplicates from Sorted Array

2019-11-15 01:08:02
字體:
來源:轉載
供稿:網友
[LeetCode] Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonceand return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,Given input arraynums=[1,1,2],

Your function should return length =2, with the first two elements ofnumsbeing1and2respectively. It doesn't matter what you leave beyond the new length.

因為這是一個sorted array。所以如果幾個數字的值相等,那么他們一定是排列在一起的。所以我們只要檢查這個數和他相鄰的數是否相等就可以了。

但注意,因為我們要output改變后的list。所以還需要一個int來輔助我們調整排列整個list。當一個數和他周圍的數不相等的話,他的位置不會有改變。但是當兩個相鄰的數相等的話,第二個數后面的一個數的位置就需要往前挪動一個了。當然如果連續3個數相等,就是往前移動2個位置了。

注意count的初始值要為1,因為除了specail case外,nums的長度至少都為1。

注意這點。其他的都好辦了。代碼如下。~

public class Solution {    public int removeDuplicates(int[] nums) {        if (nums == null || nums.length == 0)             return 0;        int count = 1;        for (int i = 1; i < nums.length; i++){            if (nums[i]!=nums[i-1]){                nums[count] = nums[i];                index++;            }        }        return count;     }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盐城市| 清镇市| 丰原市| 苏州市| 常德市| 仙桃市| 新沂市| 江陵县| 绥滨县| 青岛市| 平远县| 黄龙县| 伊吾县| 日喀则市| 县级市| 阳朔县| 岚皋县| 尼木县| 蕲春县| 绥滨县| 偃师市| 嘉义市| 修水县| 三穗县| 天津市| 江北区| 遂溪县| 湄潭县| 西宁市| 金阳县| 泰兴市| 普陀区| 玉山县| 灌云县| 门源| 万山特区| 临沭县| 西安市| 康定县| 若尔盖县| 绥江县|