A是数组:判断是否有两个整数在A中出现次数相同
A is an arrays: determine if there are two integers that are present in A the same number of times
例如:A=[1,2,2,3,4,4,5]->true; A=[1,2,2,3,3,3,4,4,4,4]->false.
proc(A){
list = newList()
for (i=1 to length[A]) {
occ = 0
n = a[i]
for (j = 1 to length[A]) {
if(a[j] == n)
occ++
}
list.append(occ)
}
但行不通,因为在列表中会重复elements.I想过使用类似于countingSort的算法,但我不知道支持向量的长度。
有什么帮助吗?在伪代码中会很好。
谢谢。
使用map和set这样的数据结构,这个任务可以很容易的完成。
Algorithm:-
-> Loop through the array and store it in hashmap with key as the value of the array element and value as the count of it's occurrence.
-> Create an empty set
-> Loop through the map and keep storing the value of every key in the set and if somewhere in between looping u come across any value that's already there in the set, then return true else if u reach the end of map, then return false.
现在让我们看一下伪代码。
Pseudocode:-
-> we have input array as arr and length n
-> we create an empty map - m[int, int]
-> for (i -> 0 to n-1)
{
m[arr[i]]++;
}
-> This in the end will give us our map which we want with key as the array element and value as it's count
-> create a set - s
-> iterate over map m as key -> value
{
if (value present in s) {
return true
}
s.insert(value)
}
-> If we reach here then it means we never came across any pair of elements whose occurrence is same, so return false.
希望对您有所帮助!
例如:A=[1,2,2,3,4,4,5]->true; A=[1,2,2,3,3,3,4,4,4,4]->false.
proc(A){
list = newList()
for (i=1 to length[A]) {
occ = 0
n = a[i]
for (j = 1 to length[A]) {
if(a[j] == n)
occ++
}
list.append(occ)
}
但行不通,因为在列表中会重复elements.I想过使用类似于countingSort的算法,但我不知道支持向量的长度。
有什么帮助吗?在伪代码中会很好。 谢谢。
使用map和set这样的数据结构,这个任务可以很容易的完成。
Algorithm:-
-> Loop through the array and store it in hashmap with key as the value of the array element and value as the count of it's occurrence.
-> Create an empty set
-> Loop through the map and keep storing the value of every key in the set and if somewhere in between looping u come across any value that's already there in the set, then return true else if u reach the end of map, then return false.
现在让我们看一下伪代码。
Pseudocode:-
-> we have input array as arr and length n
-> we create an empty map - m[int, int]
-> for (i -> 0 to n-1)
{
m[arr[i]]++;
}
-> This in the end will give us our map which we want with key as the array element and value as it's count
-> create a set - s
-> iterate over map m as key -> value
{
if (value present in s) {
return true
}
s.insert(value)
}
-> If we reach here then it means we never came across any pair of elements whose occurrence is same, so return false.
希望对您有所帮助!