Remove Duplicates from Sorted Array---leetcode 我的java题解
2015-03-26 15:45
281 查看
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 A =
Your function should return length =
这题比较简单。关键是设置一个index,指向要复盖掉重复数据的位置。从第2个数开始与前一个数比较。只要不同,就标记下要覆盖。
我写的java程序:
public int removeDuplicates(int[] A) {
int index=1;
if(A.length==0||A==null) return 0;
for(int i=1;i<A.length;i++){
if(A[i]!=A[i-1]) {
A[index] = A[i];
index++;
}
}
return index;
}
网上看到别人的写法 ,感觉更熟练。
public int removeduplicates1(int[] A){
if (A.length == 0) return 0;
int index = 0;
for (int i = 1; i < A.length; i++) {
if (A[index] != A[i])
A[++index] = A[i];
}
return index + 1;
}
===========
A[++index]这个用的挺简洁的。
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =
[1,1,2],
Your function should return length =
2, and A is now
[1,2].
这题比较简单。关键是设置一个index,指向要复盖掉重复数据的位置。从第2个数开始与前一个数比较。只要不同,就标记下要覆盖。
我写的java程序:
public int removeDuplicates(int[] A) {
int index=1;
if(A.length==0||A==null) return 0;
for(int i=1;i<A.length;i++){
if(A[i]!=A[i-1]) {
A[index] = A[i];
index++;
}
}
return index;
}
网上看到别人的写法 ,感觉更熟练。
public int removeduplicates1(int[] A){
if (A.length == 0) return 0;
int index = 0;
for (int i = 1; i < A.length; i++) {
if (A[index] != A[i])
A[++index] = A[i];
}
return index + 1;
}
===========
A[++index]这个用的挺简洁的。
相关文章推荐
- LeetCode 26. Remove Duplicates from Sorted Array 题解——Java
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- LeetCode 第二十六题(Remove Duplicates from Sorted Array) java
- [LeetCode]题解(python):080-Remove Duplicates from Sorted Array II
- Java for LeetCode 026 Remove Duplicates from Sorted Array
- LeetCode : Remove Duplicates from Sorted Array [java]
- Java for LeetCode 080 Remove Duplicates from Sorted Array II
- LeetCode 26 Remove Duplicates from Sorted Array (C,C++,Java,Python)
- [LeetCode]题解(python):026-Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array (Java)
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- LeetCode题解——Remove Duplicates from Sorted Array
- LeetCode 26 — Remove Duplicates from Sorted Array(Java)
- leetcode题解-26 Remove Duplicates from Sorted Array
- (Java)LeetCode-26. Remove Duplicates from Sorted Array
- [leetcode]26. Remove Duplicates from Sorted Array(java)
- Remove Duplicates From Sorted Array leetcode java
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- [LeetCode][Java] Remove Duplicates from Sorted Array
- LeetCode(026) Remove Duplicates from Sorted Array (Java)