Skip to content

26. 删除有序数组中的重复项

26. 删除有序数组中的重复项

代码

javascript
// 26. 删除有序数组中的重复项:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/description/
// 输入:nums = [1,1,2]
// 输出:2, nums = [1,2,_]

export function removeDuplicates (nums) {
  let left = 0
  let right = 0
  const len = nums.length
  while (right < len) {
    if (nums[left] !== nums[right]) {
      left++
      nums[left] = nums[right]
    }
    right++
  }
  return left + 1
}
typescript
// 26. 删除有序数组中的重复项:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/description/
// 输入:nums = [1,1,2]
// 输出:2, nums = [1,2,_]

export function removeDuplicates (nums: number[]): number {
  let left = 0
  let right = 0
  const len = nums.length
  while (right < len) {
    if (nums[left] !== nums[right]) {
      left++
      nums[left] = nums[right]
    }
    right++
  }
  return left + 1
}

测试代码

ts
import { expect, test } from 'vitest'
import { removeDuplicates } from './typescript.ts'
import { removeDuplicates as removeDuplicatesJs } from './javascript.js'

test(`removeDuplicates`, () => {
  const nums = [1,1,2]
  const resNums = [1, 2]
  const size = removeDuplicates(nums)
  let flag = true
  for (let i = 0; i < size; i++) {
    if (nums[i] !== resNums[i]) {
      flag = false
    }
  }
  expect(size).toBe(2)
  expect(flag).toBe(true)
})

test(`removeDuplicatesJs`, () => {
  const nums = [0,0,1,1,1,2,2,3,3,4]
  const resNums = [0,1,2,3,4]
  const size = removeDuplicatesJs(nums)
  let flag = true
  for (let i = 0; i < size; i++) {
    if (nums[i] !== resNums[i]) {
      flag = false
    }
  }
  expect(size).toBe(5)
  expect(flag).toBe(true)
})