Golang Program that Removes Duplicates Using Nested Loops
Given an array of size n. Your task is to remove the duplicates from the array.
Examples:
Input : array: 1 2 1 2 1 3 2
Output :1 2 3
Input :array: 10 24 5 10 24
Output :10 24 5
We will use two loops to solve this problem. The first loop i will traverse from 0 to the length of the array. The second loop will traverse from 0 to i-1. This loop is used to make sure that the element at index i has not come before i. If that element has come before, then we come out of the second loop. just after the second loop, we write an if condition which checks if j = = i. If they are equal, it means that the element at index i has not occurred before. So we must append the element to the result array.
package main
import "fmt"
func removeDup(a [] int , n int ) [] int {
result := [] int {}
for i := 0; i < n; i++ {
j := 0
for ; j < i; j++ {
if a[j] == a[i] {
break
}
}
if j == i {
result = append(result, a[i])
}
}
return result
}
func main() {
a := [] int {1, 2, 1, 2, 1, 3, 2}
n := 7
result := removeDup(a, n)
fmt.Println(result)
}
|
Output:
[1 2 3]
Last Updated :
17 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...