找到数组中的第二大数字

时间:2017-12-06 23:14:50

标签: javascript arrays max

我有一个像[31,23,12]这样的三个元素的数组,我想找到第二大元素及其相关位置而不重新排列数组

示例:

array = [21,23,34]
  

Second_largest = 23;

     

位置= 1;

23 个答案:

答案 0 :(得分:4)

使用.slice(0)克隆原始数组,如:

var temp_arr = arr.slice(0);

然后吸引它,这样你就可以获得数组索引temp_arr.length - 2的第二大值:

temp_arr.sort()[temp_arr.length - 2]

现在您可以使用indexOf()函数来获取此值的索引,如:

arr.indexOf(second_largest_value);



var arr = [23, 21, 34, 34];
var temp_arr = [...new Set(arr)].slice(0); //clone array
var second_largest_value = temp_arr.sort()[temp_arr.length - 2];
var index_of_largest_value = arr.indexOf(second_largest_value);

console.log(second_largest_value);
console.log(index_of_largest_value);




答案 1 :(得分:2)

使用ES6 Set Array.from

const secondLargest = (arr) => Array.from([...new Set(arr)]).sort((a,b) => b-a)[1]

上述功能使用 Set 删除重复的元素,并从排序后的数组中返回第二大元素。

答案 2 :(得分:1)

//Suggest making unique array before checking largest value in the array

    function getSecondLargest(arr) {
        let uniqueChars = [...new Set(arr)];
       
        let val=Math.max(...uniqueChars);
       
        let arr1 = arr.filter(function(item) {
        return item !== val;
        })
    
        let num=Math.max(...arr1);
        return num;
    }
    
     function main() {
         const n = +(readLine());
         const nums = readLine().split(' ').map(Number);
        
         console.log(getSecondLargest(nums));
    }

答案 3 :(得分:1)

您可以使用arrayspread创建原始sort()的副本。从你那里得到数组中的倒数第二个数字,并使用indexOf来显示它的索引。

const array = [21,23,34];
const arrayCopy = [...array];

const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));

或者,如果兼容性存在问题,您可以使用concat复制数组:

var array = [21, 23, 34];
var arrayCopy = [].concat(array);

var secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));

答案 4 :(得分:1)

这里也可以处理第二大或最大的数字是否重复

var nums =[2,3,6,6,5]; 
function getSecondLargest(nums) {
    let secondlargets;
nums.sort(function(a, b){return a - b});
// all elements are in the accesindg order
// [1,2,3,5,6,6]
var highest;
// that is the last sorted element
highest = nums[nums.length-1];

nums.pop();
// through above statment we are removing the highest element 
for(let i =0;i<nums.length-1;i++){
  if(nums[nums.length-1]==highest){
    /* here we remove gives this as conditon because might be the hiesht 
     had more indecis as we have in this question index(5) &index(6)
    so remove the element till all positon have elemnt excepts the highest */
     nums.pop()        
 }
else{
    
    return nums[nums.length-1]
/*  our array is already sorted and after removing thew highest element */
        }

    } 

} 
    

答案 5 :(得分:1)

var arr = [21,23,34];
var output = getSecondLargest(arr);

document.getElementById("output").innerHTML = output;

function getSecondLargest(nums) {
    if (nums.length == 0){
         return undefined;
    }
    nums.sort((a,b) => b-a);
    var newArr = [...new Set(nums)];
    return newArr[1];
}
<p id="output"></p>

答案 6 :(得分:1)

我尝试在不使用内置函数的情况下解决

var arr = [1,2, -3, 15, 77, 12, 55];
var highest = 0, secondHighest = 0;
// OR var highest = arr[0], secondHighest = arr[0];

for(var i=0; i<arr.length; i++){
  if(arr[i] > highest){
    secondHighest = highest;
    highest = arr[i]; 
  }

  if(arr[i] < highest && arr[i] > secondHighest){
    secondHighest = arr[i];
  }
}

console.log('>> highest number : ',highest); // 77
console.log('>> secondHighest number : ',secondHighest); // 55

答案 7 :(得分:1)

仅获得第二大数字-

arr = [21,23,34];
secondLargest = arr.slice(0).sort(function(a,b){return b-a})[1]; 

以传统方式获得第二大数字索引-

arr = [20,120,111,215,54,78];
max = -Infinity;
max2 = -Infinity;
indexMax = -Infinity;
index2 = -Infinity;

for(let i=0; i<arr.length; i++) {
    if(max < arr[i]) {
        index2 = indexMax;
        indexMax = i;
        max2 = max;
        max = arr[i];
    } else if(max2 < arr[i]) {
        index2 = i;
        max2 = arr[i];
    }
}

console.log(`index: ${index2} and max2: ${max2}`);

答案 8 :(得分:1)

我最近遇到过这个问题,但是不允许使用循环。我设法使用递归工作,因为没有其他人提出这种可能性,我决定在这里发布。 : - )

let input = [29, 75, 12, 89, 103, 65, 100, 78, 115, 102, 55, 214]

const secondLargest = (arr, first = -Infinity, second = -Infinity, firstPos = -1, secondPos = -1, idx = 0) => {
    arr = first === -Infinity ? [...arr] : arr;

    const el = arr.shift();
    if (!el) return { second, secondPos }

    if (el > first) {
        second = first;
        secondPos = firstPos;
        first = el;
        firstPos = idx;
    } if (el < first && el > second) {
        second = el;
        secondPos = idx;
    }  

    return secondLargest(arr, first, second, firstPos, secondPos, ++idx);
}

console.log(secondLargest(input));
//  {
//    second: 115,
//    secondPos: 8
//  }

希望有一天能帮助我的人。

答案 9 :(得分:1)

这种方式最冗长,但也是最具算法效率的。它只需要1次通过原始数组,不需要复制数组,也不需要排序。它也符合ES5,因为您询问可支持性。

&#13;
&#13;
var array = [21,23,34];

var res = array.reduce(function (results, curr, index) {
    if (index === 0) {
        results.largest = curr;
        results.secondLargest = curr;
        results.indexOfSecondLargest = 0;
        results.indexOfLargest = 0;
    }
    else if (curr > results.secondLargest && curr <= results.largest) {
        results.secondLargest = curr;
        results.indexOfSecondLargest = index;
    }
    else if (curr > results.largest) {
        results.secondLargest = results.largest;
        results.largest = curr;
        results.indexOfSecondLargest = results.indexOfLargest;
        results.indexOfLargest = index;
    }
    return results;
}, {largest: -Infinity, secondLargest: -Infinity, indexOfLargest: -1, indexOfSecondLargest: -1});

console.log("Second Largest: ", res.secondLargest);
console.log("Index of Second Largest: ", res.indexOfSecondLargest);
&#13;
&#13;
&#13;

答案 10 :(得分:0)

我试图在这里使答案尽可能简单,你可以超级简单

function getSecondLargest(nums) {
    var flarge = 0;
    var slarge = 0;
    for (var i = 0; i < nums.length; i++) { 
            if (flarge < nums[i]) {
                slarge = flarge;
                flarge = nums[i];
            } else if (slarge < nums[i]) { 
                if (nums[i]!=flarge){
                    slarge = nums[i];
                }
            }
        }
        return slarge; 
}

它完全合乎逻辑,这里没有数组排序或倒序,当值重复出现时,您也可以使用它。

答案 11 :(得分:0)

function getSecondLargest(nums) {
    // Complete the function
    var a = nums.sort();
    var max = Math.max(...nums);
    var rev = a.reverse();
    for(var i = 0; i < nums.length; i++) {
        if (rev[i] < max) {
            return rev[i];
        }
    }
}
var nums = [2,3,6,6,5];
console.log( getSecondLargest(nums) );

答案 12 :(得分:0)

function getSecondLargest(nums) {
  let arr = nums.slice();//create a copy of the input array
  let max = Math.max(...arr);//find the maximum element
  let occ = 0;
    for(var i = 0 ; i < arr.length ; i++)
    {
        if(arr[i] == max)
        {
            occ = occ +1;//count the occurrences of maximum element
        }
    }

    let sortedArr =arr.sort(function(x, y) { return x > y; } );//sort the array

    for(var i = 1 ; i <= occ ; i++){
        sortedArr.pop()//remove the maximum elements from the sorted array
    }


    return Math.max(...sortedArr);//now find the largest to get the second largest



}

答案 13 :(得分:0)

查找第二个最高数字(数组包含重复的值)

const getSecondHighestNumber = (numbersArry) =>  {
  let maxNumber = Math.max( ...numbersArry);
  let arrFiltered = numbersArry.filter(val => val != maxNumber);
  return arrFiltered.length ? Math.max(...arrFiltered) : -1;
}
let items = ["6","2","4","5","5","5"];
const secondHighestVal = getSecondHighestNumber(items);
console.log(secondHighestVal); // 5

答案 14 :(得分:0)

function getSecondLargest(nums) {
nums.sort(function(x,y){
       return y-x;
    });
for(var j=1; j < nums.length; j++)
 {
    if(nums[j-1] !== nums[j])
    {
         return nums[j];
    }
 }
}
getSecondLargest([1,2,3,4,5,5]);

输出: 4

此方法还将处理数组中数字的多次出现。在这里,我们首先对数组进行排序,然后忽略相同的数字并返回答案。

答案 15 :(得分:0)

/* we can solve it with recursion*/
     let count = 0;    /* when find max then count ++ */
     findSecondMax = (arr)=> {
       let max = 0;  /* when recursive function call again max will reinitialize and we get latest max */
         arr.map((d,i)=>{
            if(d > max) {
                max = d;
            }
            if(i == arr.length -1) count++;
         })
/* when count == 1 then we got out max so remove max from array and call recursively again with rest array so now count will give 2 here we go with 2nd max from array */
       return count == 1 ? findSecondMax(arr.slice(0,arr.indexOf(max)).concat(arr.slice(arr.indexOf(max)+1))) : max;
    }

    console.log(findSecondMax([1,5,2,3]))

答案 16 :(得分:0)

const array = [21, 23, 34];

function getSecondLargest(array) {
  let largest = 0
  let secondLargest = 0
  for (let i = 0; i < nums.length; i++) {
    if (largest < nums[i]) {
      largest = nums[i]
      secondLargest = largest
    }
    if (secondLargest < nums[i] && largest > nums[i]) {
      return (secondLargest = nums[i])
    }
  }
  return secondLargest
}

getSecondLargest(array);

答案 17 :(得分:0)

我使用两个变量 maxsecondMax 以简单的交换逻辑编写了具有 O(n) 复杂度的最简单函数。

function getSecondLargest(nums) {
  let max = 0, secondMax = 0;
  nums.forEach((num) => {
    if (num > max) {
        secondMax = max;
        max = num;
    } else if (num != max && num > secondMax) secondMax = num;
  });
  return secondMax;
}

答案 18 :(得分:0)

简单的递归函数,可找到n个最大的数字而无需排列 any 数组:

编辑:在有多个相等大数的情况下也适用。

let array = [11,23,34];

let secondlargest = Max(array, 2);
let index = array.indexOf(secondlargest);

console.log("Number:", secondlargest ,"at position", index);

function Max(arr, nth = 1, max = Infinity) {
  let large = -Infinity;
  for(e of arr) {
    if(e > large && e < max ) {
      large = e;
    } else if (max == large) {
      nth++;
    }
  }
  if(nth==0) return max;
  return Max(arr, nth-1, large);
}

答案 19 :(得分:0)

function getSecondLargest(nums) {
  const sortedArray = new Set(nums.sort((a, b) => b - a)).values();
  sortedArray.next();

  return sortedArray.next().value;
}

console.log(getSecondLargest([1, 2, 4, 4, 3]));

答案 20 :(得分:0)

请找到一个简单的解决方案,不使用内置函数:

时间复杂度为 O(n)

function secondLargest(arr) {
        let prev = [0]
        let i =1;
        let largest =0;
        while(i<arr.length){
            let current = arr[i];
            if(current > largest ) {
                largest = current;
                prev = arr[i-1];
            } else if (current > prev && current < largest) {
                prev = current
            }
            i++;
        }
        return prev;
    }
    
    let arr = [1,2,3,41,61,10,3,5,23];
    console.log(secondLargest(arr));

答案 21 :(得分:0)

var elements = [21,23,34]

var largest = -Infinity

// Find largest 
for (var i=0; i < elements.length; i++) {
  if (elements[i] > largest) largest = elements[i]
}

var second_largest = -Infinity
var second_largest_position = -1

// Find second largest
for (var i=0; i < elements.length; i++) {
  if (elements[i] > second_largest && elements[i] < largest) {
    second_largest = elements[i]
    second_largest_position = i
  }
}

console.log(second_largest, second_largest_position)

答案 22 :(得分:-1)

function getSecondLargest(nums) {
  const len = nums.length;
  const sort_arr = nums.sort();
  var mynum = nums[len-1];
  for(let i=len; i>0; i--){
    if(mynum>nums[i-1]){
        return nums[i-1]; 
    }
  }
}