LeetCode 26.Remove Duplicates from Sorted Array
来源:互联网 发布:java迭代器遍历list 编辑:程序博客网 时间:2024/05/17 05:12
LeetCode 26.Remove Duplicates from Sorted Array
Description:
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 by modifying the input array in-place with O(1) extra memory.
Example:
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 new length.
分析:
注意这道题加了限制,在O(1)空间复杂度实现,且该数组已排序
可以弄一个变量temp,初始置为0,循环判断是否和相邻的数相等,若不等,则更新temp的值(+1),同时nums[temp]更新为相邻的一个数(后面的数),最后返回temp+1则是该结果。
代码如下:
#include <iostream>#include <algorithm>#include <vector>#include <set>using namespace std;class Solution {public: int removeDuplicates(vector<int>& nums) { if (nums.size() == 0) return 0; int temp = 0; for (int i = 1; i < nums.size(); i++) { if (nums[temp] != nums[i]) { temp++; nums[temp] = nums[i]; } } return temp + 1; }};int main() { Solution s; vector<int> nums; int n; cin >> n; int t; for (int i = 0; i < n; i++) { cin >> t; nums.push_back(t); } cout << s.removeDuplicates(nums) << endl; return 0;}
阅读全文
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
- 21、访问者模式(Visitor)
- eclipse 配置连接hadoop集群
- idea+maven+ssm+shiro开发shiro权限登录,验证码
- 怎么和甲方交流
- 《C程序设计语言》【PDF】下载链接:
- LeetCode 26.Remove Duplicates from Sorted Array
- Spring Cloud云服务架构
- 初识EasyUI
- 22、中介者模式(Mediator)
- solr多字段、打分规则、权重和实时索引同步
- jq ajax同步失败,原因之一
- Recyclerview自定义点击事件
- android调用系统浏览器
- Golang从入门到精通(一):Golang介绍