【LeetCode】26. Remove Duplicates from Sorted Array
来源:互联网 发布:知乎 不氪金的手游 编辑:程序博客网 时间:2024/05/17 06:06
题目描述:
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 arraynums =[1,1,2]
,
Your function should return length =2
, with the first two elements ofnums being1
and2
respectively. It doesn't matter what you leave beyond the new length.
不要为另一个数组分配额外的空间,您必须在内存不变的情况下这样做。
例如:给定输入数组nums=[1,1,2],您的函数应该返回长度=2,而nums的前两个元素分别是1和2。你在新的长度之外留下什么并不重要。
这是第一次做的时候的解法:
class Solution { public int removeDuplicates(int[] nums) { int n = nums.length; for(int i = 0; i<n-1;){ if(nums[i]==nums[i+1]){ for(int j=i+1;j<n-1;j++){ nums[j]=nums[j+1]; } n--; }else{ i++; } } return n; }}
我的最初的想法是数组中的第一个与后面的每一个比较,如果相等,就把后面的依次往前移动,所以有了上面的解法,时间复杂度是O(n²)。后来看了参考答案,时间复杂度是O(n),参考答案相当于用了两个指针,i和j,i从0开始,i所指过的地方都是不与前面重复的,j的作用就是用来找那个不重复的数,找到以后赋值给i所指的地方。用两个指针这样的解法确实没有想到,也很少在做题中用到,不过这次学到了。
public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1;}
阅读全文
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
- c基础第7课-数组及简单字符串操作
- 【自翻】Andrew Ng作业大纲 Ex1(中文)
- 数据结构知识点概括
- Linux的互斥锁
- Python异常处理
- 【LeetCode】26. Remove Duplicates from Sorted Array
- 何谓电子信息?
- 将前台数据成批插入后台数据库
- name="applicable-device" 屏幕适配
- 高通 8x26 andorid light sensor(TSL258x) 开发
- CentOS7卸载wordpress
- 2017 ACM-ICPC 亚洲区(乌鲁木齐赛区)网络赛
- LintCode解题记录17.9.9
- C++大数相加