[leetcode note] 3Sum Closest

折月煮酒 提交于 2019-12-17 02:40:27

时间: 2019-12-16 8:14 PM
题目地址: https://leetcode.com/problems/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.

给定一个已排序的数组num,原地删除重复项,以使每个元素仅出现一次并返回新的长度。

不要为另一个数组分配额外的空间,必须通过使用O(1)额外的内存就地修改输入数组来做到这一点。

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.

Solution:

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

Runtime: 1 ms, faster than 97.92% of Java online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 40.3 MB, less than 77.13% of Java online submissions for Remove Duplicates from Sorted Array.

欢迎关注公众号(代码如诗):
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!