首页 新闻 会员 周边 捐助

求高效实现一个算法

0
悬赏园豆:10 [已解决问题] 解决于 2016-11-09 09:36

有四种颜色不一的球,每个球都有若个,都标有不同大小的数字,随机排序,求算法实现找到四种颜色上面数字最小的四个球

不要问我从哪里来123的主页 不要问我从哪里来123 | 初学一级 | 园豆:6
提问于:2016-11-01 18:38
< >
分享
最佳答案
0

var balls=[];
//fill some data
balls.push({color:"red",number:1});
balls.push({color:"blue",number:4});
balls.push({color:"yellow",number:10});
balls.push({color:"green",number:4});
balls.push({color:"red",number:3});
balls.push({color:"blue",number:5});
balls.push({color:"yellow",number:8});
balls.push({color:"green",number:2});
balls.push({color:"red",number:4});
balls.push({color:"blue",number:8});
balls.push({color:"yellow",number:7});
balls.push({color:"green",number:2});
balls.push({color:"red",number:6});
balls.push({color:"blue",number:3});
balls.push({color:"yellow",number:1});
balls.push({color:"green",number:14});

var redball,blueball,greenball,yellowball;

for(var i=0;i<balls.length;i++){
  switch(balls[i].color){
    case "red":
      if(redball==null)
        redball=balls[i];
      else{
        if(redball.number>balls[i].number)
        redball=balls[i];
      }
      break;
    case "blue":
      if(blueball==null)
        blueball=balls[i];
      else{
        if(blueball.number>balls[i].number)
          blueball=balls[i];
      }
      break;
    case "yellow":
      if(yellowball==null)
        yellowball=balls[i];
      else{
        if(yellowball.number>balls[i].number)
          yellowball=balls[i];
      }
      break;
    case "green":
      if(greenball==null)
        greenball=balls[i];
      else{
        if(greenball.number>balls[i].number)
          greenball=balls[i];
      }
      break;
   }
}

 

result:

Object {color: "red", number: 1}

Object {color: "green", number: 2}

Object {color: "yellow", number: 1}

Object {color: "blue", number: 3}

收获园豆:10
王维强 | 菜鸟二级 |园豆:212 | 2016-11-02 17:36
其他回答(4)
0

O(n)吧

jello chen | 园豆:7336 (大侠五级) | 2016-11-01 20:03
0

无序的遍历一次就行了.4个变量记每种颜色最小球.每个都对比一次.

所有查找算法都要基于有序的数据

吴瑞祥 | 园豆:29449 (高人七级) | 2016-11-01 20:05
0

先判颜色,再判大小就可以了,最好是两次遍历,如果想省市,网上很多数组提取最小数。

张云山 | 园豆:642 (小虾三级) | 2016-11-02 09:00
0

你题目是不是记错了?这几种颜色并没有增加难度,你就看成是单色的找最小O(n)不就完了么?

Daniel Cai | 园豆:10424 (专家六级) | 2016-11-02 15:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册