leetcode 26. Remove Duplicates from Sorted Array 头部双指针
2017-09-01 16:45
351 查看
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.
这道题就是要求去除所有的重复元素,然后统计数量并返回。
最最直接的想法就是使用set,但是题目要求空间复杂度是O(1),所以直接设置一个index表示不重复的元素的下标,同时也是最终的length。
代码如下:
下面是C++做法
代码如下:
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.
这道题就是要求去除所有的重复元素,然后统计数量并返回。
最最直接的想法就是使用set,但是题目要求空间复杂度是O(1),所以直接设置一个index表示不重复的元素的下标,同时也是最终的length。
代码如下:
/* * 寻找重复的元素并不断的向前移动 * */ public class Solution { public int removeDuplicates(int[] nums) { if(nums.length<=1) return nums.length; int res=1; for(int i=1;i<nums.length;i++) { if(nums[i]!=nums[i-1]) nums[res++]=nums[i]; } return res; } }
下面是C++做法
代码如下:
#include <iostream> #include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.size() <= 1) return nums.size(); int len = 1; for (int i = 1; i < nums.size(); i++) { if (nums[i] != nums[i - 1]) nums[len++] = nums[i]; } return len; } };
相关文章推荐
- 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
- [leetcode]--26. Remove Duplicates from Sorted Array
- [leetcode26] Remove Duplicates from Sorted Array
- leetcode-26. Remove Duplicates from Sorted Array 78.84%
- [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 (easy)
- LeetCode 26 - Remove Duplicates from Sorted Array
- leetcode-26-Remove Duplicates from Sorted Array