[leetcode]Remove Duplicates from Sorted Array(Java实现)
2017-05-23 19:33
399 查看
本题为leetcode题库28:
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 =
Your function should return length =
It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
牛客网测试地址:https://www.nowcoder.com/questionTerminal/a519784e89fb40199fbe7993786715b1
Java代码如下:
package go.jacob.day523;
public class Demo1 {
public int removeDuplicates(int[] nums) {
//异常输入
if(nums==null||nums.length<=1)
return nums==null?0:nums.length;
int count=1;
for(int i=1;i<nums.length;i++){
//如果数组当前元素与前一个元素不同,则加入新数组
if(nums[i]!=nums[i-1])
nums[count++]=nums[i];
}
return count;
}
}
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
1and
2respectively.
It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
牛客网测试地址:https://www.nowcoder.com/questionTerminal/a519784e89fb40199fbe7993786715b1
Java代码如下:
package go.jacob.day523;
public class Demo1 {
public int removeDuplicates(int[] nums) {
//异常输入
if(nums==null||nums.length<=1)
return nums==null?0:nums.length;
int count=1;
for(int i=1;i<nums.length;i++){
//如果数组当前元素与前一个元素不同,则加入新数组
if(nums[i]!=nums[i-1])
nums[count++]=nums[i];
}
return count;
}
}
相关文章推荐
- [leetcode]Remove Duplicates from Sorted Array II(Java实现)
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- Remove Duplicates from Sorted Array II--leetcode 我的java题解
- Java [leetcode 26]Remove Duplicates from Sorted Array
- leetcode-java-26. Remove Duplicates from Sorted Array
- [LeetCode][Java] Remove Duplicates from Sorted Array II
- LeetCode : Remove Duplicates from Sorted Array [java]
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- leetcode:Remove Duplicates from Sorted Array 【Java】
- Leetcode 26. Remove Duplicates from Sorted Array (Easy) (java)
- [LeetCode][Java] Remove Duplicates from Sorted Array
- [LeetCode-Java]26. Remove Duplicates from Sorted Array
- LeetCode – Remove Duplicates from Sorted Array (Java)
- Remove Duplicates from Sorted Array II leetcode java
- Remove Duplicates from Sorted Array leetcode java
- LeetCode(080) Remove Duplicates from Sorted Array II (Java)
- Java for LeetCode 026 Remove Duplicates from Sorted Array
- Leetcode:26. Remove Duplicates from Sorted Array(JAVA)
- Java for LeetCode 080 Remove Duplicates from Sorted Array II
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】