Skip to content

Latest commit

 

History

History
55 lines (49 loc) · 1.46 KB

26.md

File metadata and controls

55 lines (49 loc) · 1.46 KB

26. 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.

给定一个有序数组,删除重复的元素,确保每个元素只出现一次,返回删除元素后数组的长度。

解法1

循环,直接比较nums[i]nums[i+1]是否相等,相等则删除,效率有点低。

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
  if (nums.length <= 1) return nums;

  for (var i = 0; i < nums.length; i++) {
    while(nums[i+1] === nums[i]) {
      nums.splice(i + 1, 1);
    }
  }
  return nums.length;
};
161 / 161 test cases passed.
Status: Accepted
Runtime: 260 ms

解法2

不使用js的splice方法,直接将不想等的元素复制。

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
  if (nums.length <= 1) return nums;

  var j = 1;
  for (var i = 1; i < nums.length; i++) {
    if (nums[i-1] !== nums[i]) nums[j++] = nums[i];
  }
  return j;
};
161 / 161 test cases passed.
Status: Accepted
Runtime: 216 ms