我在JavaScript中编写了代码,但问题是启动值ex:? - 9,?-87 ... etc
Input: {88, 105, 3, 2, 200, 0, 10}
<script type="text/javascript">
function RangeValues(){
var a = [88, 105, 3, 2, 200, 0, 10];
var n = a.length;
var pq = [];
for(var i = 0; i<n; i++) {
if(a[i] >= 0 && a[i] <= 99)
pq.push(a[i]);
}
var start = 0;
if(!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
while(pq.length != 0)
{
var num = pq.last();
pq.pop();
if(num - start > 1){
console.log( (start) +','+ (num-1));
}
if((num - start) == 1)
{
start = num + 1;
console.log(start);
}
}
if(start == 99){
console.log('99');
}
else if(start < 100) {
console.log(start+' to '+99);
}
return 0;
}
RangeValues();
</script>
actual output: 0-9,0-1,0-2,0-87,0-99 Expected: 1,4-9,11-87,89-99
答案 0 :(得分:0)
首先,您应该对数组pq
中的数字进行降序排序,以便最后一个值是最小数字。尝试使用以下解决方案:
function RangeValues(){
var a = [88, 105, 3, 2, 200, 0, 10];
//var a = [12, 105, 23, 1, 200, 4, 21];
var n = a.length;
var pq = [];
for(var i = 0; i<n; i++) {
if(a[i] >= 0 && a[i] <= 99){
pq.push(a[i]);
}
}
// sort array descending
pq.sort(function(a, b){return b-a});
var start = 0;
if(!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
while(pq.length != 0){
var num = pq.last();
pq.pop();
if (num-start == 2 || num == 1){
console.log(num-1);
} else if((num - start)>2){
var from = start + 1;
var end = num - 1;
console.log(from+" - "+end);
}
start = num;
}
if (start < 98){
var from = start + 1;
console.log(from+" - "+99);
} else if( start == 98){
console.log(start+1);
}
return 0;
}
RangeValues();
&#13;