Remove Duplicates from Sorted Array
来源:互联网 发布:武侠台词 知乎 编辑:程序博客网 时间:2024/05/29 20:04
Problem: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.
题目的要求不仅返回长度,同时原数组删除了重复元素。
public static int removeDuplicates(int[] nums) {int len=nums.length,i=0,j=1;if(len<2)return len;while(j<len){if(nums[i]==nums[j])j++;elsenums[++i]=nums[j++];}return i+1;}
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being
1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
public static int removeDuplicates(int[] nums) {int len=nums.length,i=1,j=2;if(len<=2)return len;while(j<len){if(nums[i]==nums[j]&&nums[i-1]==nums[j])j++;else{i++;nums[i]=nums[j];j++;}}return i+1;}
0 0
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- UVA 401
- c++string
- CEF Xilium.CefGlue 防止浏览器闪退
- (网络视频监控)面试题12
- 交互模式下python自动补全
- Remove Duplicates from Sorted Array
- linux常用命令
- 锁屏效果
- 高阶函数 Higher-order function
- [UVA400]Unix ls[格式输出]
- Java NIO原理图文分析及代码实现
- C# 之 string字符串
- Divisibility by Eight
- POJ 2752 Seek the Name, Seek the Fame(KMP)