S2 icon indicating copy to clipboard operation
S2 copied to clipboard

0026. Remove Duplicates From Sorted Array | LeetCode Cookbook

Open halfrost opened this issue 4 years ago • 9 comments

https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0026.Remove-Duplicates-from-Sorted-Array/

halfrost avatar Feb 15 '21 03:02 halfrost

func removeDuplicates(nums []int) int {
	res,dup,len:= 0,0,len(nums)
	for i:=0;i<len;i++{
		if i==0{
			res++
		}else{
			if nums[i-dup]!=nums[i-dup-1]{
				res++
			}else{
			    nums = append(nums[:i-dup],nums[i-dup+1:]...)
				dup++
			}
		}
	}
	return res
}

hujun2020 avatar Aug 06 '21 11:08 hujun2020

func RemoveDuplicate(arr []int) (lenght int) {
	m := make(map[int]int)
	for i := 0; i < len(arr); i++ {
		if _, ok := m[arr[i]]; !ok {
			m[arr[i]] = i
		} else {
			continue
		}
	}
	return len(m)
}

Aixleft723 avatar Aug 22 '21 03:08 Aixleft723

用map也可以吧

zhangguolei avatar Nov 02 '21 02:11 zhangguolei

@zhangguolei 用 map 也可以。

halfrost avatar Nov 07 '21 06:11 halfrost

func removeDuplicates(nums []int) int { if len(nums) == 0 { return 0 }

curNum := nums[0]
counter := 1 

for i := 1; i < len(nums); i++ {
    if nums[i] > curNum {
        curNum = nums[i]
        nums[counter] = curNum 
        counter++
    }        
}

return counter

}

shiyin-weng avatar Feb 04 '22 06:02 shiyin-weng

@sunkai-XDD

func RemoveDuplicate(arr []int) (lenght int) {
	m := make(map[int]int)
	for i := 0; i < len(arr); i++ {
		if _, ok := m[arr[i]]; !ok {
			m[arr[i]] = i
		} else {
			continue
		}
	}
	return len(m)
}

这个 continue 显的过分多余😄

rsmelody avatar Apr 06 '22 08:04 rsmelody

func removeDuplicates(nums []int) int {
    RETRY:
    for i:=0;i<len(nums);i++{
        if i + 1 < len(nums) && nums[i] == nums[i+1]{
           nums = append(nums[:i], nums[i+1:]...) 
           goto RETRY
        }
    }
    return len(nums)
}

虽然性能和时间都一般。。但算是利用Go的特性?😅

JOJO0527 avatar Jun 04 '22 16:06 JOJO0527

题目要求 Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

@halfrost @zhangguolei 用 map 也可以。

nofrish avatar Sep 13 '22 09:09 nofrish

func removeDuplicates(nums []int) int {
	i, j := 0, 0
	for j < len(nums)-1 {
		if nums[j] == nums[j+1] {
			j++
			continue
		}
		i++
		j++
		nums[i] = nums[j]
	}

	return i + 1
}

nofrish avatar Sep 13 '22 09:09 nofrish