解决这个问题最省时的方法是什么?

时间:2019-10-21 15:54:30

标签: c++

我们有五个不同的数字。写下三个最大数字的总和。 1 <= x <= 10000 我尝试用if else编写if else,但这不是很节省时间。之后,我尝试在if(a> b && b> c等)等其他语句中编写更多语句,但这也确实很慢,因为我需要编写很多内容。

2 个答案:

答案 0 :(得分:3)

  1. 将五个数字放入数组
  2. 按降序排列此数组,将最高编号放在首位
  3. 最后,只需从排序后的数组中获取前三个数字并将它们加在一起即可。

答案 1 :(得分:1)

Manually order the first three to highest, middle, lowest
Compare the 4th with the lowest, and either
  discard 4th
or
  discard lowest
  compare with middle to select new lowest from 4th or middle

Compare 5th with new lowest, and either
  discard 5th
or 
  discard lowest

add up the 3 numbers

与第4个数字相加时,与任何排序算法相比,这节省了1个运算,其中第4个数字高于前3个数字中的最高数字,因为前3个数字中的最高数字永远不会被其他2个数字丢弃。

进一步避免了使用排序算法插入第5个数字,但这还是很明显的。

在第一个子句中将Compare 5th子句写入3次意味着数据处理量略少,但代码更多:

Compare the 4th with the lowest, and either
  (discard 4th)
  Compare 5th with lowest, and either
    add up 5th middle, highest
  or 
    add up lowest middle highest
or
  compare with middle to select new lowest from 4th or middle
    (4th)
    Compare 5th with 4th, and either
      add up 5th middle, highest
    or 
      add up 4th middle highest
 or
    Compare 5th with middle, and either
      add up 5th, 4th, highest
    or 
      add up 4th middle highest

另一种选择是考虑要丢弃的两个条目,而不是保留的三个条目:

Order the first 2 entries to higher and lower 
If 3rd entry is lower than higher 
  If 3rd is lower than lower
    lower -> higher ; 3rd -> lower
  else
    3rd -> higher
If 4th entry is lower than higher 
  If 4th is lower than lower
    lower -> higher ; 4th -> lower
  else
    4th -> higher
If 5th entry is lower than higher 
  5th to higher
Sum all the entries except lower and higher, 
or sum /all/ the entries then subtract lower and higher

对于要尝试或保留的大量条目,规范的方法是维护具有正确数量要保留的元素的堆。当考虑下一个元素时,将其与堆头进行比较,如果“更好”,则“重估”堆头并将其冒泡到正确的位置。 “重估/气泡头”通常不是堆管理代码的标准功能,但易于实现,比删除旧的头然后插入新的节点要快。

相关问题