LeetCode 26:Remove Duplicates from Sorted Array

作者: LiHui 分类: LeetCode 发布时间: 2018-07-22 21:41

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.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

题目长篇大论的,意思就是传入一个列表,返回去掉重复数字后,只出现一次的元素个数

刚开始题目没看清,没看到是已经排序好的数组,排序好的就比较简单了,不能用其他内存空间

NewImage

i遍历整个nums,current作为非重复数组的下标

i递增,如果nums[i] == nums[currentIndex],无视;如果nums[i] != nums[currentIndex],currentIndex++,并赋值为i位置的值,说明又多了一个不重复的新元素,继续往后进行

这里currentIndex从0开始的,最后长度++即可,如果是从1开始,就不需要++了

源码如下

package com.lihuia.leetcode26;

/**
* Copyright (C), lihuia.com
* FileName: Solution
* Author: lihui
* Date: 2018/7/22
*/

public class Solution {

public int removeDuplicates(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
int currentIndex = 0;
//nums: 0 0 0 1 1 2 3 4 4 4
//index: 0 1 2 3 4 5 6 7 8 9
//curr: 0 1 2 3 4
for (int i = 0; i < len; i++) {
if (nums[i] != nums[currentIndex]) {
currentIndex++;
nums[currentIndex] = nums[i];
}
}
currentIndex++;
return currentIndex;
}
}

空数组也带上

纯属恶搞

浙ICP备16024533号

浙公网安备 33010802007459号