LeetCode 26.Remove Duplicates from Sorted Array
2017-12-12 09:44
507 查看
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; }
相关文章推荐
- leetcode 26. Remove Duplicates from Sorted Array
- LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)
- leetcode 26. Remove Duplicates from Sorted Array
- [LeetCode] 26 Remove Duplicates from Sorted Array
- [leetcode 26] Remove Duplicates from Sorted Array
- LeetCode 26 remove Duplicate 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(java)
- 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 (easy)
- 【LeetCode】C# 26、Remove Duplicates from Sorted Array
- Leetcode26-Remove Duplicates from Sorted Array
- [leetcode]26. Remove Duplicates from Sorted Array
- [LeetCode]26. Remove Duplicates from Sorted Array