0

javscript 第二大没有。代码请帮我解决这个程序

function getSecondLargest(nums) {
    // Complete the function
    nums.sort();
    //console.log("sorted array", nums);
    let largest_no = nums[nums.length-1];
    let final_array = nums.filter(x => x != largest_no);
    let second_largest_no = final_array[final_array.length-1]
    console.log("filtered array", final_array);
    return second_largest_no;
}
getSecondLargest([2, 2, 1, 2, 5,  1, 5, 3, 4, 6, 6 , 6 , 5 , 5]);
4

2 回答 2

0

如果他们通过忽略重复来寻找“5”作为第二大数字。然后下面的代码可用于查找第二个最大值。

可以根据您的要求设置“Default_Min”。该算法将具有 O(n) 时间复杂度。这比使用排序和过滤要好。

function SencondLargest(nums)
{
    let max_1;
    let max_2;
    let Default_Min = 0;

    if (nums.length < 2) 
    { 
        console.log(" Invalid Input "); 
        return; 
    }
    max_1 = max_2 = Default_Min;
    for(let i=0; i<nums.length; i++)
    {
        if (nums[i] > max_1) 
        { 
              max_2 = max_1; 
              max_1 = nums[i]; 
        } 
        else if (nums[i] > max_2 && nums[i] != max_1) 
                max_2 = nums[i];
    }

    if (max_2 == Default_Min) 
        console.log("There is no second largest"+ " element\n"); 
    else
        console.log("The second largest element"+ " is "+ max_2); 
}

var x = [2, 2, 1, 2, 5,  1, 5, 3, 4, 6, 6 , 6 , 5 , 5];
SencondLargest(x);
于 2020-04-20T12:05:27.210 回答
0

尝试使用reduce具有O(N)复杂性的方法。所以我们可以使用reducemethod来遍历数组,并获得诸如方法largeValue: 0, largerValue: 0, largestValue: 0累加器之类的值reduce

const obj = arr.reduce((a, c, i) => {
   a[c] = a[c] || {c};
   if (i === 0) {
      a.largeValue = c;
      a.largerValue = c;
      a.largestValue = c;
   }
   else {
      if (c > a.largeValue && c < a.largerValue && c > a.largestValue) {
         a.largeValue = c;
      }
      else if (c > a.largeValue && c > a.largerValue) {
         if (a.largerValue == a.largestValue) {
            a.largerValue = c;
         }
         else {
            a.largestValue = c;
         }
      }
   }
   return a;
},{ largeValue: 0, largerValue: 0, largestValue: 0 });

一个例子:

let arr = [2, 2, 1, 2, 5,  1, 5, 3, 4, 6, 6 , 6 , 5 , 5];

const obj = arr.reduce((a, c, i) => {
   a[c] = a[c] || {c};
   if (i === 0) {
      a.largeValue = c;
      a.largerValue = c;
      a.largestValue = c;
   }
   else {
      if (c > a.largeValue && c < a.largerValue && c > a.largestValue) {
         a.largeValue = c;
      }
      else if (c > a.largeValue && c > a.largerValue) {
         if (a.largerValue == a.largestValue) {
            a.largerValue = c;
         }
         else {
            a.largestValue = c;
         }
      }
   }
   return a;
},{ largeValue: 0, largerValue: 0, largestValue: 0 });

console.log(obj.largerValue);

于 2020-04-20T13:19:00.763 回答