您的位置:首页 > 其它

26 Remove Duplicates from Sorted Array

2015-08-16 17:17 288 查看
题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

题目:

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.


解题思路:

使用两个指针 i (指向有序且无重复的序列的最后一位数字)和 j (指向 i 指针之后的元素)

i 初始为 0,j 初始为 1

在 j 小于数组最大下标的前提下,比较 i 和 j 所指元素是否相等

相等,则执行 j ++ 操作。重复执行该过程,直到 i 和 j 所指元素不等为止

不相等,则将 j 当前所指元素复制到 i 所指元素的后继位置

直到 j 的大小等于数组长度时,退出外部大循环

此时,新数组的长度为 i + 1

注意:

比较 i 和 j 所指元素是否相等之前,必须先判断 j 的大小是否已超出数组范围

public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int len = nums.length;
int i = 0;
int j = 1;
while(j < len) {
while(j < len && nums[j] == nums[i])
j ++;
if(j == len)
break;
nums[++ i] = nums[j ++];
}
return i + 1;
}
}


161 / 161 test cases passed.
Status: Accepted
Runtime: 368 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: