ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

26. Remove Duplicates from Sorted Array

2019-03-13 22:37:32  阅读:191  来源: 互联网

标签:26 return nums Duplicates ++ int length 数组 Sorted


题目:

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 2respectively.

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.

中文题意:

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

示例 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4

你不需要考虑数组中超出新长度后面的元素。

说明:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

你可以想象内部操作如下:

1 // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
2 int len = removeDuplicates(nums);
3  
4 // 在函数里修改输入数组对于调用者是可见的。
5 // 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
6 6 for (int i = 0; i < len; i++) {
7 7     print(nums[i]);
8 8 }

 

方法:双指针法

C++:

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if (nums.size() == 0) return 0;
 5         
 6         int i = 0;  //第一个”指针“指向数组第一个位置
 7         for (int j = 1; j < nums.size(); j++) {  //第二个”指针“指向数组的第二个位置,开始遍历一边数组
 8             if (nums[j] != nums[i]) 
 9                 nums[++i] = nums[j];
10         }
11          return i + 1;
12     }
13 };

官方题解:

 

算法:

数组完成排序后,我们可以放置两个指针 i 和 j,其中 i 是慢指针,而 j 是快指针。只要 nums[i] = nums[j],我们就增加 j 以跳过重复项。

当我们遇到 nums[j] ≠ nums[i] 时,跳过重复项的运行已经结束,因此我们必须把它(nums[j])的值复制到 nums[i + 1]。然后递增 i,接着我们将再次重复相同的过程,直到 j 到达数组的末尾为止。

Java:

 1 public int removeDuplicates(int[] nums) {
 2     if (nums.length == 0) return 0;
 3     int i = 0;
 4     for (int j = 1; j < nums.length; j++) {
 5         if (nums[j] != nums[i]) {
 6             i++;
 7             nums[i] = nums[j];
 8         }
 9     }
10     return i + 1;
11 }

 

复杂度分析

  • 时间复杂度:O(n), 假设数组的长度是 n,那么 i 和 j 分别最多遍历 n 步。

  • 空间复杂度:O(1)。

 

标签:26,return,nums,Duplicates,++,int,length,数组,Sorted
来源: https://www.cnblogs.com/Anonym077/p/10527176.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有