Find out the maximum number of two (K) in an unordered array

Source: Internet
Author: User

* * give you an integer array, I want to find out the largest two number, can help me write an algorithm?

**
In the last time we have read the question, including the one we can think of. Here we follow the general steps to solve the problem of algorithms to analyze the problem together:

First, make sure that we understand the problem and try an example to make sure that you understand it correctly.
Now let's clarify the problem, we need to find the largest two digits from {4, 5,2,3,1} in such an array to return {4,5}, and we return an empty array when the array is empty.
Second, think about how you can solve the problem, which one you will choose, why?
We don't want to sort him out first, because there are two, the array is the reference type, the sorting will change the original data results, I believe you call others SDK, certainly do not want their data inexplicably changed, right, even if we can guarantee not to change the original order, we will also introduce additional storage space, in addition, There is no requirement to have all the numbers sorted back, and the sort seems wasteful. Moreover, the general sort is best able to do n log (n), and this problem actually only need O (n) can solve.
Third, explain your algorithm and the method of implementation
Explaining our algorithm, we declare two temporary variables, Max, Secondmax, and then start scanning the array. If the current number in the array is larger than Max, we'll replace it with Max, which, of course, assigns Max to Secondmax before replacing it, and if the current number in the array is smaller than Max, we'll compare if it's larger than Secondmax, We'll assign it directly to Secondmax, and we won't have to deal with it in any other situation.
Four, write code, remember, must explain what you are doing

public static int[] Findmaxtwo (int[] array) {//If the input array is empty, or the length of the array is only one, we do not have to deal with it and return directly if (array = = NULL | | array.             Length = = 1) return array; Define two temporary variables and think about why we are assigning a value of int.minvalue int max = Int.             MinValue; int secondmax = Int.             MinValue; Begins scanning array for (int index = 0; index < array. Length; index++) {//If the current number is larger than Max, we will change the value of Secondmax and then the table Max if (Array[index] >= ma                     X) {Secondmax = max;                 max = Array[index];                 }//If the current number is not larger than Max, but larger than Secondmax, we directly change the value of Secondmax else if (Array[index] >= Secondmax)                 {Secondmax = Array[index];             }}//Well, we'll get these two values in the array, ready to return int[] result = new INT[2];             Result[0] = Secondmax;             RESULT[1] = max; Return ResULt   }

V. Take an example, work through your code (omitted ha)
Six, repair defects, to ensure that abnormal conditions are taken into account. We need to list some of the special cases here, if the same number is present in an array, and it is the largest number, what do we return? such as {5,3,4,1,5}, return {4,5} or {5,5}, the different requirements will differ in the details of the processing. If the array is full of negative numbers, can our code return the expected results?

Try it: you can put intmax= Int. MinValue; int secondmax = Int. MinValue, change to Intmax;int Secondmax; try { -5,-2,-4,-3,-1} again, there will be a bug. The root cause is that the default value of int is 0.
Try again: We define two temporary variables, then declare an array, is not a bit wasteful. Not concise, is there? OK, let's give it a little bit of an optimization:

  public static int[] FindMaxTwoImproved2 (int[] array) {if (array = = NULL | | array.             Length = = 1) return array; Here's a bug when the max value was negative since the initial value in the Int. array is 0 int[] result = N             EW int[2]; This was to fix the bug above for (var index = 0; index < result. Length; index++) {Result[index] = Int.             MinValue;             } Console.WriteLine (Result[1]); for (int index = 0; index < array. Length;  index++) {if (Array[index] >= result[0]) {result[0] =                     RESULT[1];                 RESULT[1] = Array[index];                 } else if (Array[index] >= result[1]) {result[0] = Array[index];         }} return result; }  

Back to the previous question, we have asked whether K will change, can do status quo, dynamic some, you let us return a few we return a few? Of course, this time we will declare an array of length k, and look directly at the code:

 Let's extend the array to get K fliexable public static int[] FindMaxTwoImproved3 (int[] array, int K)              {if (K < 0) throw new ArgumentException ("The k should not being negative."); if (array! = NULL && array.              Length < K) throw new ArgumentException ("The k should less than the length of target array."); if (array = = NULL | | array.              Length = = 1) return array; Here's a bug when the max value was negative since the initial value in the Int. array is 0 int[] result =              New Int[k]; This was to fix the bug above for (var index = 0; index < result. Length; index++) {Result[index] = Int.              MinValue; } for (int index = 0; index < array. Length; index++) {if (Array[index] >= result[k-1]) {&lt ; span style= "Background-color:rgb (51,204,0);" >for (inT fallback = 0; Fallback < k-1; fallback++) </span> <span style= "Background-color:rgb (51,204,0);" > {</span> <span style= "Background-color:rgb (51,204,0);" > Result[fallback] = result[fallback + 1];</span> <span style= "Background-color:rgb (51 , 204,0); " >}</span> <span style= "Background-color:rgb (51,204,0);"                  ></span> result[k-1] = Array[index];                      } else {for (int fallback = k-1; fallback >= 0; fallback--)                              {if (Array[index] >= Result[fallback]) { <span style= "Background-color:rgb (51,204,0);" >for (int fallback2 = 0; Fallback2 < fallback; fallback2++) </span> <span style= "Background-color:rgb (51,2 04,0); " > {</span> &LT;SPAn style= "Background-color:rgb (51,204,0);" > Result[fallback2] = result[fallback2 + 1];</span> <span style= "Background-co Lor:rgb (51,204,0); "                          >}</span> Result[fallback] = Array[index];          }}}} return result;   }

In this code, have you found that there is a suspicion of duplication of code? I've got them all highlighted up. We'll define a public method,

/// <summary>        /// 改方法会负责将当前数组array从前往后的K-1个数字依次赋值成后面的数组,        /// 而最后一个值我们将替换成target        /// </summary>        /// <param name="array"></param>        /// <param name="target"></param>        /// <param name="k"></param>        public static void Fallback(int[] array, int target, int k)        {            if (k > 0)            {                for (int fallback2 = 0; fallback2 < k - 1; fallback2++)                {                    array[fallback2] = array[fallback2 + 1];                }                array[k - 1] = target;            }        }  

Replace the highlighted section with the last code:

Let's remove the duplication code public static int[] FindMaxTwoImproved4 (int[] array, int k) {             if (K < 0) throw new ArgumentException ("The k should not being negative."); if (array = = NULL | | array.             Length = = 1) return array; Here's a bug when the max value was negative since the initial value in the Int. array is 0 int[] result = N             EW Int[k]; This was to fix the bug above for (var index = 0; index < result. Length; index++) {Result[index] = Int.             MinValue; } for (int index = 0; index < array. Length; index++) {if (Array[index] >= result[k-1]) {Fallbac                     K (result, Array[index], k);                 RESULT[K-1] = Array[index];           } else {for (int fallback = k-1; fallback >= 0; fallback--)          {if (Array[index] >= Result[fallback]) {                             Fallback (result, Array[index], Fallback);                         Result[fallback] = Array[index];         }}}} return result;   }

Did everyone find out? This is not a sort of algorithm we have seen. Yes, when k = N, this is the insertion order that opens up new storage space. Do you have?
Next we can define a variety of inputs to test our algorithm, here is an example. For everyone's reference:

static void Main(string[] args)        {            int[] array = new int[5] { -5, -3, -4, -5, 10 };            var result = FindMaxTwo(array);            PrintArray(result);            result = FindMaxTwoImproved4(array, 2);            PrintArray(result);        }        public static void PrintArray(int[] array)        {            if (array == null)            { Console.WriteLine("The array is null or empty"); }            else            {                foreach (var i in array)                {                    Console.Write(i + "  ");                }                Console.WriteLine();            }        }  

You are welcome to pay attention to my public number, as well as my series of video tutorials , data structures and algorithms and classical algorithms to guide questions, sorting lectures, List of topics .

Everyone has a better solution, also welcome to discuss Kazakhstan.

Find the maximum number of two (K) in an unordered array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.