Home > Net >  Why is it wrong to use if here,in golang,remove-duplicates-from-sorted-array
Why is it wrong to use if here,in golang,remove-duplicates-from-sorted-array

Time:11-14

  1. I am a beginner and hope to get your help

  2. it is remove-duplicates-from-sorted-array

    func remove(nums []int)int{
     i,j:= 0,0
    
    
     //Why is it wrong to use if here?
     // if j< len(nums)
     for j < len(nums){
         if i==0 || nums[i-1]!= nums[j]{
             nums[i] = nums[j]
             i  
             j  
         }else{
             j  
         }
     }
     return i
    

    }

      func main(){
         nums := []int{1,2,2,3,5,5}
         result := remove(nums)
         fmt.Println(result)
       }
    
  3. please help me

CodePudding user response:

On short notice, here's what I have:

func remove(nums []int) int {
  temp := map[int]string{}
  for _, n := range nums {
    temp[n] = "exist"
  }
  result := []int{}
  for n, _ := range temp {
    result = append(result, n)
  }
  return result
}

And the output is:

[1 2 3 5]

Iterate through the slice and put into a map. Iterate through the map and put into a slice. Return the new slice.

CodePudding user response:

It is a sorted list of numbers, so you can store the last number added into the results list and skip adding into the result list if the next number is the same.

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

    result := []int{nums[0]}
    current := nums[0]
    for _, num := range nums {
        if current == num {
            continue
        }
        
        result = append(num)
        current = num
    }
    
    return result
}

If you are asking about why is it wrong to use for j < len(nums), its not wrong, but using for _, num := range nums would make your life easier as you don't have to keep track of where you are in the array.

  • Related