最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Understanding get second lowest and second highest value in array - Stack Overflow

programmeradmin2浏览0评论

Good day fellow Stack-ers,

I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).

I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.

Here is my answer:

var array = [3,8,5,6,5,7,1,9];
var outputArray = [];

function arrayTrim() {
  var sortedArray = array.sort();
  outputArray.push(sortedArray[1],array[array.length-2]);
  return outputArray;
}

arrayTrim();

and here is the answer that they have provided:

function Second_Greatest_Lowest(arr_num) {  
  arr_num.sort(function(x,y) {  
    return x-y;
  });  

  var uniqa = [arr_num[0]];  
  var result = [];  

  for(var j=1; j < arr_num.length; j++) {  
    if(arr_num[j-1] !== arr_num[j]) {
      uniqa.push(arr_num[j]);  
    }  
  }

  result.push(uniqa[1],uniqa[uniqa.length-2]);
  return result.join(',');  

}  

alert(Second_Greatest_Lowest([1,2,3,4,5])); 

I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.

Thank you!

Good day fellow Stack-ers,

I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).

I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.

Here is my answer:

var array = [3,8,5,6,5,7,1,9];
var outputArray = [];

function arrayTrim() {
  var sortedArray = array.sort();
  outputArray.push(sortedArray[1],array[array.length-2]);
  return outputArray;
}

arrayTrim();

and here is the answer that they have provided:

function Second_Greatest_Lowest(arr_num) {  
  arr_num.sort(function(x,y) {  
    return x-y;
  });  

  var uniqa = [arr_num[0]];  
  var result = [];  

  for(var j=1; j < arr_num.length; j++) {  
    if(arr_num[j-1] !== arr_num[j]) {
      uniqa.push(arr_num[j]);  
    }  
  }

  result.push(uniqa[1],uniqa[uniqa.length-2]);
  return result.join(',');  

}  

alert(Second_Greatest_Lowest([1,2,3,4,5])); 

I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.

Thank you!

Share Improve this question edited Sep 6, 2017 at 19:26 user7858585 asked Jan 27, 2016 at 12:25 Aaron MatthewsAaron Matthews 1284 silver badges13 bronze badges 6
  • What happens in your solution if my numbers are 1,2,3,4,5,5 - do I get the second to highest number from your function? What about the provided correct solution? – Jamiec Commented Jan 27, 2016 at 12:28
  • It seems to sort them (as numbers, not lexically as you do), then it filters out duplicates by pushing only unique values to uniqa, then it takes the second-lowest and second-highest value from that. – Bergi Commented Jan 27, 2016 at 12:28
  • 1 It should have been forbidden to use sort() in this challenge. – Danny_ds Commented Jan 27, 2016 at 12:58
  • what makes you say that @Danny_ds? I'd be interested to hear you rationale – Aaron Matthews Commented Jan 28, 2016 at 6:22
  • @AaronMatthews - Sort() is a very expensive operation ( O(n log n) at best) and needs random access to the data (a lot). It is not needed at all to find the two numbers - those can be found using one sequential pass through the data (which also better utilizes the cpu cache). Since this is a learning exercise/challenge they should have forbidden to use sort(). Of course, on 10 numbers it won't make a big difference, but on millions (or even data that won't fit in memory) it will. You'll understand this even better after solving exercise no. 24 (bubble sort) on that same page. – Danny_ds Commented Jan 28, 2016 at 10:34
 |  Show 1 more ment

3 Answers 3

Reset to default 3

Your answer does not perform correct for input such as f.e. [3,8,5,6,5,7,1,1,9]. Your proposed solution returns 1 as the second lowest number here – whereas it should actually be 3.

The solution suggested by the site takes that into account – that is what the if inside the loop is for, it checks if the current number is the same as the previous one. If that’s the case, it gets ignored. That way, every number will occur once, and that in turn allows to blindly pick the second element out of that sorted array and actually have it be the second lowest number.

It seems like a long way around to the solution

You took a short cut, that does not handle all edge cases correctly ;-)

The loop in question:

for(var j=1; j < arr_num.length; j++) {  
    if(arr_num[j-1] !== arr_num[j]) {
      uniqa.push(arr_num[j]);  
    }  
  }

Provides some clue as to what it's doing by using a (reasonably) descriptive variable name: uniqa - or "unique array". The if statement is checking that the current element is not the same as the previous element - having sorted the array initially this works to give you a unique array - by only filling a new array if the element is indeed unique.

Thereafter the logic is the same as yours.

import java.util.Arrays;

public class BubbleWithMax_N_Min
{
    public static void main(String[] agrs)
    {

        int temp;
        int[] array = new int[5];
        array[0] = 3;
        array[1] = 99;
        array[2] = 55;
        array[3] = 2;
        array[4] = 1;

        System.out.println("the given array is:" + Arrays.toString(array));
                for (int i = 0; i < array.length; i++)
                {
                    System.out.println(array[i] + "");
                }

                for (int i = 0; i < array.length; i++)
                {

                    for (int j = 1; j < array.length - i; j++)
                    {

                        if (array[j - 1] > array[j])
                        {

                            temp = array[j - 1];
                            array[j - 1] = array[j];
                            array[j] = temp;

                        }

                    }
                }

                System.out.println(" 2nd Min and 2nd Highest:");
                for (int i = 0; i < 1; i++)
                {
                    System.out.println(array[i+1]);

                }
        for (int i = 0; i < 1; i++)
        {
            int a= array.length-2;
            System.out.println(array[a]);

        }

            }
        }
发布评论

评论列表(0)

  1. 暂无评论