码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:26. Remove Duplicates from Sorted Array(Easy)

时间:2017-12-29 12:24:45      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:des   public   题目   string   moved   code   out   system   技术   

1. 原题链接

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

2. 题目要求

给定一个已经排序的整数数组nums[ ],返回除去重复元素后的数组长度

注意:不能重新创建一个数组,空间复杂度为O(1)

3. 解题思路

使用指针j来遍历数组,i用来计数。初始时,i指向nums[0],j指向nums[1]。

当nums[i] != nums[j]时,i++,且nums[i]=nums[j],从j所在元素位置继续比较。

最后返回 i+1

4. 代码实现

public class RemoveDuplicatesFromSortedArray26 {
    public static void main(String[] args) {
        int nums[] = {2, 2, 3, 4, 5, 5, 6};
        System.out.println(removeDuplicates(nums));
    }

    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) { //不相等时i++
                i++;
                nums[i] = nums[j];
            }
        }

        return i + 1;
    }
}

 运行结果:

技术分享图片

 

LeetCode:26. Remove Duplicates from Sorted Array(Easy)

标签:des   public   题目   string   moved   code   out   system   技术   

原文地址:https://www.cnblogs.com/huiAlex/p/8143070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!