在特定时刻获得胜利者的功能

时间:2017-03-27 20:58:54

标签: algorithm sorting dictionary time-complexity memoization

我想与更聪明的程序员讨论最近一次采访中提出的这个问题,引导您完成我的方法,并询问您将如何有效地解决这个问题。非常感谢您的见解:)

假设您有一个数组:

 arr = [[sam,123],[ram,124],[kris,125],[hen,127],[kris,135], [sam,140],...] 

其中每个单元格代表候选名称和时间戳(正在增加并且连续添加新记录)。这个数组可以有数百万条记录。

编写一个函数findWinner(arr,timestamp),它返回获胜者的名字,直到该时间戳,给定时间戳可能在给定数组中,也可能不在给定数组中。打印领带“领带”

我的方法:

方法1:

a. Create a function voteCount(mydict, a) which takes an entry a and stores the count of each candidate in a dictionary and returns a dictionary say mydict
b. Create a function getMax(mydict) which takes the dictionary mydict created and sorts the dictionary with respect to values(count here), checks if there is a repeat (names) with respect to max as one edge case and print out "tie" or prints out the name of the max candidate
c. Create a function findWinner(arr, timestamp) which takes the input array arr, and a given timestamp and iterate through each entry in the array untill the given timestamp and take the name arr[i][0] and call voteCount(mydict, arr[i][0]) on it. 
d. After the loop finishes run getMax on mydict and print out the results

I was thinking of memoization in this scenario because there was no space constraints

方法2:

a. Create a datastructure Node with a name and count like the one below:

class Node
 attr_accessor :name, :count
 def initialize(name,count)
  @name = name
  @count = count
 end
end
b. In the getMax(mydict), take each key value pair as a node in a heap and run a max-heapify function with node.count and print out the root name(For edge case of tie, we can check with root's left child and right child)

1 个答案:

答案 0 :(得分:3)

创建SortedMap<Integer, Set<String>>(例如红黑树),其中键是时间戳,值是该时间戳的获胜者名称。还要创建一个Map<String, Integer>,其中键是名称,值是分数(初始化为零)。接下来,遍历数组:

SortedMap<Integer, Set<String>> timestampMap = new RedBlackTree()
Map<String, Integer> scoreMap = new HashMap()
Set<String> currentWinners

foreach [name, timestamp] in array {
  int currentNameScore = scoreMap.get(name) + 1
  scoreMap.put(name, currentNameScore)
  int currentWinnerScore = scoreMap.get(currentWinners.first())
  if(currentWinners.contains(name) || currentNameScore > currentWinnerScore) {
    currentWinners = new Set(name)
  } else if(currentWinnerScore == currentNameScore) {
    currentWinners = currentWinners.copy().add(name)
  }
  timestampMap.put(timestamp, currentWinners)
}

您使用Map来跟踪每个姓名的当前得分,然后您可以确定姓名的得分现在是等于还是超过当前获胜者的得分。查询给定时间戳的SortedMap(如果给定的密钥不存在,则紧接在时间戳之前)是O(log(n))操作。 (例如,参见SortedMap作为SortedMap上典型操作的示例。初始化SortedMap是一个O(n * log(n))操作,因此只有使用它才有意义如果您对数据进行多次查询(否则您的线性搜索更快),这种方法。