力扣:初级算法——26. 删除排序数组中的重复项

题目:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array

示例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 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if(nums.size()<=1)  return nums.size();
 5         int len=nums.size();
 6         int i,j=1;
 7         int count=0;
 8         for(i=0;i<len;i++){
 9             while(j<len&&(nums[j]==nums[i])){
10                 j++;
11             }
12             if(j<len){                  //判断j是否超出范围
13                 nums[i+1]=nums[j];      //遇到不同的直接替换
14                 count++;
15             }
16         }
17         return count+1;
18     }
19 };

稍微修改一下,思路是一样的,这样更好看一些:

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if(nums.size()<=1)  return nums.size();
 5         int len=nums.size();
 6         int i=0,j=0; 7         while(j<len){
 8             if(nums[i]!=nums[j]){
 9                 nums[++i]=nums[j];
10             }
11             j++;
12         }
13         return i+1;
14     }
15 };

猜你喜欢

转载自www.cnblogs.com/pananni/p/13192845.html