如何在推送中删除重复的值?

huangapple go评论75阅读模式
英文:

How do i remove duplicate valeus in push?

问题

这可能是一个初学者的问题...

如何在不推送值的情况下删除重复的值?

当值为("lorem", "ipsum", 1, 1, 1, "jack", "jill", "felix", "donking")时,应该打印出("lorem", "ipsum", 1, "jack", "jill", "felix", "donking")

如何在上述的push函数中删除重复的值?

// 推送值
func (q *Data) Push(n interface{}) *Data {
	if q.Len() < q.size {
		q.data = append(q.data, n)
		if q.data[q.Len()] == q.data[q.Len()+1] {
			q.Pop()
			q.Push(n)
		}
	} else {
		q.Pop()
		q.Push(n)
	}
	return q
}
英文:

This might be noob question...

How to remove the duplicate values instead pushing values?

When the values was:(&quot;lorem&quot;, &quot;ipsum&quot;, 1, 1, 1, &quot;jack&quot;, &quot;jill&quot;, &quot;felix&quot;, &quot;donking&quot;)<br/>
It should print:(&quot;lorem&quot;, &quot;ipsum&quot;, 1, &quot;jack&quot;, &quot;jill&quot;, &quot;felix&quot;, &quot;donking&quot;)

How to remove this duplicated values in push function like above?

// Push values
func (q *Data) Push(n interface{}) *Data {
	if q.Len() &lt; q.size {
		q.data = append(q.data, n)
		if q.data[q.Len()] == q.data[q.Len()+1] {
			q.Pop()
			q.Push(n)
		}
	} else {
		q.Pop()
		q.Push(n)
	}
	return q
}

答案1

得分: 2

每种数据结构都使用底层的原始数据结构进行实现,看起来你正在使用一个切片(slice)。如果你只想保存唯一的数据,你应该使用一个map。为了在仅用于查找重复项时尽可能高效地使用map,你可以使用map[interface{}]struct{}

英文:

Every data structure uses an underlying primitive data structure for implementation, and it looks like you are using a slice. If you only want to save unique data, you should use a map. In order to be as efficient as possible when using a map only for finding duplicates, you can use a map[interface{}]struct{}.

答案2

得分: 0

需要检查队列中的数据与推送的值进行比较。如果数据已经在队列中,则应返回。

for i := range q.data {
    if q.data[i] == n {
        return q // 当n的值等于q.data中的某个值时,返回q。
    }
}
q.data = append(q.data, n)
英文:

One needs to check the data in the queue against the pushed value. If the data was already in the queue it should returned.

for i := range q.data {
    if q.data[i] == n {
        return q // return q when n value is found equal to one of q.data values.
    }
}
q.data = append(q.data, n)

huangapple
  • 本文由 发表于 2021年12月21日 12:46:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/70430790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定