专栏首页leetcode_solutions26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

【题目】

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

【实现】

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 【每天一道编程系列-2018.3.6】(Ans)

    Given an array S of n integers, are there elements a, b, c in S such that a + b ...

    yesr
  • 1. Two Sum(HashMap储存数组的值和索引)

    Given an array of integers, return indices of the two numbers such that they add...

    yesr
  • 【每天一道编程系列-2018.3.7】(Ans)

      Given an array S of n integers, find three integers in S such that the sum is ...

    yesr
  • 【Leet Code】26. Remove Duplicates from Sorted Array

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

    韩旭051
  • Q26 Remove Duplicates from Sorted Array

    Given a sorted array, remove the duplicates in-place such that each element appe...

    echobingo
  • leetcode334. Increasing Triplet Subsequence

    假设有一个无序的数组,如果数组中从左到右存在三个由小到大的数字,则返回true。否则返回false。

    眯眯眼的猫头鹰
  • Golang Leetcode 189. Rotate Array.go

    版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89011736

    anakinsun
  • LeetCode第27题

    Given an array nums and a value val, remove all instances of that value in-place...

    用户3112896
  • Array - 283. Move Zeroes

    Given an array nums, write a function to move all 0's to the end of it while mai...

    用户5705150
  • Leetcode之删除排序数组中的重复项

    每个数组的长度都是大于等于1的,遍历数组,如果遇到不同的就加一,这里尽量不用len函数

    润森

扫码关注云+社区

领取腾讯云代金券