有四种颜色不一的球,每个球都有若个,都标有不同大小的数字,随机排序,求算法实现找到四种颜色上面数字最小的四个球
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}
O(n)吧
无序的遍历一次就行了.4个变量记每种颜色最小球.每个都对比一次.
所有查找算法都要基于有序的数据
先判颜色,再判大小就可以了,最好是两次遍历,如果想省市,网上很多数组提取最小数。
你题目是不是记错了?这几种颜色并没有增加难度,你就看成是单色的找最小O(n)不就完了么?