[LeetCode][JavaScript]Remove Duplicates from Sorted Array

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.

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

 

 

 


 

 

 

从有序数组中删除重复的元素。

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var removeDuplicates = function(nums) {
 6     var aRemove = [], i, previous;
 7     for(i = 0; i < nums.length; i++){
 8         if(nums[i] === previous){
 9             aRemove.push(i);
10         }
11         previous = nums[i];
12     }
13     for(i = aRemove.length - 1; i >= 0; i--){
14         nums.splice(aRemove[i], 1);
15     }
16     return nums.length;
17 };

 

 

 

 

posted @ 2015-10-18 17:14  `Liok  阅读(521)  评论(0编辑  收藏  举报