【leetcode】26. Remove Duplicates from Sorted Array
来源:互联网 发布:php goto语句 编辑:程序博客网 时间:2024/06/16 13:10
一、题目描述
Given a sorted array, 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 in place with constant memory.
For example,
Given input array 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 new length.
题目解读:给出一个序列,去掉序列中重复的元素,返回不重复序列的长度n,且数组的前n个元素就是这个不重复序列。
思路:设置两个指针,通过比较两个元素,如果相同就往后移,不相同就赋值到前面元素的位置。
c++代码(40ms,20.83%)
class Solution {public: int removeDuplicates(vector<int>& nums) { int len = nums.size(); if(len == 0 || len == 1) return len; int start = 0; int end = 1; while(end < len){ while((nums[start] == nums[end]) && (end<len)){ end++; } if(end<len){ nums[start+1]=nums[end]; } if(end>=len && nums[start] == nums[end-1]) break; start++; end++; } return start+1; }};
一份更简洁的代码(34ms,40.26%)
class Solution {public: int removeDuplicates(vector<int>& nums) { int n = nums.size(); int count = 0; for(int i = 1; i < n; i++){ if(nums[i] == nums[i-1]) count++; else nums[i-count] = nums[i]; } return n-count; }};
0 0
- [LeetCode]26.Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode --- 26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- [Leetcode] 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- 【leetcode】 26. Remove Duplicates from Sorted Array
- [leetCode]26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array LeetCode
- 【LeetCode】26. Remove Duplicates from Sorted Array
- [LeetCode]26. Remove Duplicates from Sorted Array
- leetcode 26. Remove Duplicates from Sorted Array
- LeetCode *** 26. Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode - 26. Remove Duplicates from Sorted Array
- leetcode-26. Remove Duplicates from Sorted Array
- 26.[Leetcode]Remove Duplicates from Sorted Array
- [UITableview问题]使用UITableBarController加UITableView时,底部被遮挡
- GDI+学习笔记之GDI+环境初始化
- 高手速成android开源项目【项目篇】
- Erasure Coding(纠删码)深入分析
- 【复习】servlet之ConnectionDataBase
- 【leetcode】26. Remove Duplicates from Sorted Array
- Export aborted because fatal lint errors were found.
- 机器学习Coursera下载和存档
- 一路编程,一路迷茫,一路醒悟,接着迷茫,再醒悟再迷茫
- EventBus使用详解(一)——初步使用EventBus
- Redis高可用架构(1)—
- 再分析Reanalysis和诊断模型Diagnostic Model定义
- iOS的优秀开源项目
- LeetCode 357. Count Numbers with Unique Digits