英文:
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:("lorem", "ipsum", 1, 1, 1, "jack", "jill", "felix", "donking")
<br/>
It should print:("lorem", "ipsum", 1, "jack", "jill", "felix", "donking")
How to remove this duplicated values in push function like above?
// Push values
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
}
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论