• 欢迎来到莫知我哀的博客,日常不定时更新C++、C#、Unity、OpenGL、游戏开发相关文章。同步博客: CSDN
  • 网站左下角可以开启好听的背景音乐~~
  • 如果您觉得本博客很有看点,那么赶紧使用Ctrl+D 收藏吧

[LeetCode] 26. Remove Duplicates from Sorted Array

算法练习 wahh 384次浏览 0个评论 扫描二维码

题目

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]);
}

 

原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

 

题意

输入一个已经排序好的数组,删除数组中重复的数字,输出剩余数组长度,并将剩余数字按照原本的顺序放置在数组的首部。注意,额外空间复杂度要求为O(1)。

 

分析

定义变量x为当前不重复的数据个数,线性扫描数组,将新的数放置到x位置并将x++。

 

代码

 


莫知我哀 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:[LeetCode] 26. Remove Duplicates from Sorted Array
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
Title - Artist
0:00