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 in place with constant memory.
限定条件:
不要重新开辟一个新数组空间,在原地操作
问题描述:
给一个已经排好序的数组,删除里面的重复元素,保证最后数组中每个元素只出现一次,最后返回处理过数组的长度。
解法一:
思路:
在Java语言中,所有的非原始数据类型(int double char boolean)都是对象,例如数组和字符串也是对象。另外数组支持迭代,所以可以用foreach语句迭代每个元素。在循环体中只有当前元素大于前一个元素,那么才把当前迭代值赋给数组对应位置,并且将索引i加1。循环结束后,返回索引值i,也就是处理过的数组的长度。
Code:
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for(int n : nums){
if(i == 0 || n > nums[i-1]){
nums[i++] = n;
}
}
return i;
}
}
trick:
这里的||运算符有短路求值(short circuit evaluation)特点 ,第一个condition为真,后面的condition就不做了,直接进入循环,所以不会有nums[-1]的情况
解法二:
思路:
去掉了i ==0 情况 ,看的还不太明白,大致的意思是第一个元素不会改变
Code:
public int removeDuplicates(int[] nums) {
int i = nums.length > 0 ? 1 : 0;
for (int n : nums)
if (n > nums[i-1])
nums[i++] = n;
return i;
}
解法三:
哈希表
public class Solution {
/**
* @param nums an array of integers
* @return the number of unique integers
*/
public int deduplication(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0){
return 0;
}
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++){
set.add(nums[i]);
}
int index = 0;
for (int num : set){
nums[index++] = num;
}
return set.size();
}
}
解法四
同向双指针,注意先自增len…
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
int len = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] != nums[len]){
nums[++len] = nums[i];
}
}
return len + 1;
}
}