Created
June 22, 2019 17:24
-
-
Save ardovic/e77dac8ac6a127d87388006538ef769b to your computer and use it in GitHub Desktop.
Sample solution to an algorithmic problem (Find two missing numbers in an array)
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
| class FindTwoMissingNumbersInArray { | |
| public static void main(String args[]) { | |
| int[] arrInput = new int[]{7, 0, 1, 2, 5, 3, 4, 6}; | |
| System.out.println("For input array: " + Arrays.toString(arrInput)); | |
| int maxVal = arrInput.length + 1; | |
| int sumMiss = getReqSum(maxVal) - getRealSum(arrInput, maxVal); | |
| int avgMiss = sumMiss / 2; | |
| int missSmall = getReqSum(avgMiss) - getRealSum(arrInput, avgMiss); | |
| System.out.println("Missing numbers are: " + missSmall + " and " + (sumMiss - missSmall)); | |
| } | |
| static int getReqSum(int n) { | |
| return n * (n / 2) + (n % 2 == 0 ? n / 2 : n); | |
| } | |
| static int getRealSum(int[] arr, int maxVal) { | |
| int sum = 0; | |
| for (int i : arr) { | |
| if (i <= maxVal) | |
| sum += i; | |
| } | |
| return sum; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment