题目:选出数组a中距离8最近的10个数?
数组a:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
1 var num = 10; 2 var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; 3 var t = 0; 4 for (var i = 0; i < a.length; i++) { 5 if (a[i] == 17) { 6 t = i; 7 }; 8 }; 9 a.splice(t, 1); 10 if(t<num/2){ 11 console.info(a.slice(0, num)); 12 }else if(t+num/2 > a.length){ 13 console.info(a.slice(a.length-10)); 14 }else{ 15 console.info(a.slice(t-num/2, t+num/2)); 16 } 17 18 console.info(t);
距离最近的意思:7和9距离8的距离是相同的,
3种情况:
- 8的前后距离的元素不相同,前面距离少于10/2
- 8的前后距离的元素不相同,前面距离少于10/2
- 8的前后距离的元素相同
时间: 2024-11-09 05:35:15