leetcode 26. Remove Duplicates from Sorted Array
来源:互联网 发布:金钻淘宝店有哪些 编辑:程序博客网 时间:2024/06/05 22:36
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。
代码如下:
/* * 寻找重复的元素并不断的向前移动 * */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; }};
阅读全文
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
- 收获,不止SQL优化——抓住SQL的本质--第十章
- 程序,进程,线程(任务)
- 搭建ftp服务器
- POJ3617
- python协程与异步I/O
- leetcode 26. Remove Duplicates from Sorted Array
- mysql-jdbc 6.0 serverTimezone参数详解
- 抓取360图片
- Java基础总结---IO流
- 俄国资安服务商发现可关闭英特尔管理引擎的方式
- VMware共享文件夹
- Python3之阻塞I/O,非阻塞I/O及I/O多路复用
- pdf在线预览
- HOSTOJ 1101: 那些四位数