Created
April 8, 2013 04:38
-
-
Save richzw/5334268 to your computer and use it in GitHub Desktop.
Given a array of integers , find 3 indexes i, j, k such that, i<j<k and a[i] < a[j]< a[k]. Could you find possible O(n) algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * @func: find the ascends element from array | |
| * @params: arr{array}, the given array, | |
| * len{int}, the length of array | |
| * pos{int}, the first position that finding the ascending elements | |
| */ | |
| 43 void findAscend_(int arr[], int len, int pos){ | |
| 44 int index_array[ARRLEN] = {0}; | |
| 45 int current_max = 0; | |
| 46 int current_max_index = 0; | |
| 47 if (arr == NULL || pos >= len) | |
| 48 return ; | |
| 49 | |
| 50 //initialize the index array. traverse the array from back to front | |
| 51 for (int index = len - 1; index >= 0; --index){ | |
| 52 if (arr[index] > current_max){ | |
| 53 current_max_index = index; | |
| 54 current_max = arr[index]; | |
| 55 } | |
| 56 index_array[index] = current_max_index; | |
| 57 } | |
| 58 | |
| 59 int current = arr[pos]; | |
| 60 for (int index = pos; index < len - 1; ++index){ | |
| 61 if (arr[index] > current && index_array[index] > index) | |
| 62 { | |
| 63 cout << "the ascends are: " << current << " " | |
| 64 << arr[index] << " " | |
| 65 << arr[index_array[index]] << endl; | |
| 66 return; | |
| 67 } | |
| 68 } | |
| 69 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment