找到仍有机会赢得大选的候选人人数

时间:2016-04-06 10:10:57

标签: java algorithm

选举正在进行中!

鉴于目前为每位候选人提供的一系列投票数,  还有一个整数k,即尚未投票的选民人数,   找到仍有机会赢得选举的候选人人数。

选举的获胜者必须获得比任何其他候选人更多的选票。  如果两名或两名以上候选人获得相同(最多)票数,   假设根本没有胜利者。

实施例

对于投票= [2,3,5,2]和k = 3,输出应为 electionsWinners(votes,k)= 2。

对于投票= [1,3,3,1,1]和k = 0,输出应为 electionsWinners(votes,k)= 0。

对于投票= [5,1,3,1,4]和k = 0,输出应为 electionsWinners(votes,k)= 1。

int electionsWinners(int[] votes, int k) {

int max = votes[0];
int counter = 0;

/* I assumed all the voters who haven't cast their vote,
 votes only 1 candidate */

for(int i = 1; i < votes.length; i++) {
    //getting the candidate who has the highest vote.
    if(votes[i] > max ) {
        max = votes[i];
    }
}

// count the candidates who still have the chance to win.
for(int i = 0; i < votes.length; i++) {
    if(k != 0){
         if((votes[i] + k) > max) {
        counter++;
        }       
    } else if(k == 0) {
        /* if there is no voters left to vote, 
        and the candidates who has the highest vote will be the winner. 
        and if two or more candidates recieve the same(maximum) number of votes,
        assume there is no winner. */

        // count the no. of candidates who recieve the same(maximum) number of votes.
         if(votes[i] == max) {
        counter++;
             if(counter == 1) {
                 counter = 1;
             } else {
                 counter = 0;
             }
        } 
    }
}
return counter;
}

我是编程的初学者。尽我所能解决它,这就是我的代码。我只是想知道是否有简化的解决方案。

2 个答案:

答案 0 :(得分:2)

我认为您的代码不适用于k = 0,并且投票数最多的候选人数等于2 * n + 1,例如[1, 3, 3, 3, 1]
为什么?由于这一部分:

if(votes[i] == max) {
  counter++;
  if(counter == 1) {
     counter = 1;
  } else {
     counter = 0;
  }
}

因此,如果到目前为止您找到了2名拥有最多选票的候选人,则重置计数器。然后,当您找到另一个时,将其增加到1,如果没有更多具有最多投票的候选人,则返回1,这显然是不正确的。

循环中的代码应该只是

...
} else if (k == 0 && votes[i] == max) {
  counter++;
}

for循环之外,您可以快速检查

if (k == 0 && counter > 1)
  counter = 0;

答案 1 :(得分:1)

首先,您当前的解决方案不正确。特别是代码

->nodeValue

非常奇怪:如果counter等于1,则将其设置为1无效。当library(RCurl) library(rjson) json <- getURL('https://extraction.import.io/query/runtime/17d882b5-c118-4f27-8ce1-90085ec0b116?_apikey=d5a8a01e20174e95887dc0f385e4e3f6d7ef5ca1428d5a029f2aa352509948ade8e5d7fb0dc941f4769a32b541ca6b38a7cd6578dfd81b357fbc4f2e008f5154f1dbfcff31878798fa887b70b1ff59dd&url=http%3A%2F%2Fwww.numbeo.com%2Fcost-of-living%2Fcompare_cities.jsp%3Fcountry1%3DSingapore%26country2%3DAustralia%26city1%3DSingapore%26city2%3DMelbourne') obj <- fromJSON(json) if (counter == 1) { counter = 1; } ... 时会发生什么:k == 0在0和1之间切换,这不是您想要的。尝试使用3位投票最多的候选人来解决问题。

您正确地观察到有两种情况:如果counter,您必须检查每位候选人是否在所有剩余选民投票给他/她时他/她将获胜。如果k != 0,您必须检查是否有单个候选人获得最高票数。因此,我希望您的代码看起来像以下伪代码:

k == 0