# 求高效实现一个算法

0

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}

0

O(n)吧

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

0

0

Daniel Cai | 园豆：10424 (专家六级) | 2016-11-02 15:30

您需要登录以后才能回答，未注册用户请先注册