|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | + |
| 9 | +/** |
| 10 | + * 1228. Missing Number In Arithmetic Progression |
| 11 | + * |
| 12 | + * In some array arr, the values were in arithmetic progression: the values arr[i+1] - arr[i] are all equal for every 0 <= i < arr.length - 1. |
| 13 | + * Then, a value from arr was removed that was not the first or last value in the array. |
| 14 | + * Return the removed value. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: arr = [5,7,11,13] |
| 18 | + * Output: 9 |
| 19 | + * Explanation: The previous array was [5,7,9,11,13]. |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * Input: arr = [15,13,12] |
| 23 | + * Output: 14 |
| 24 | + * Explanation: The previous array was [15,14,13,12]. |
| 25 | + * |
| 26 | + * Constraints: |
| 27 | + * 3 <= arr.length <= 1000 |
| 28 | + * 0 <= arr[i] <= 10^5 |
| 29 | + * */ |
| 30 | +public class _1228 { |
| 31 | + public static class Solution1 { |
| 32 | + /**A super verbose and inefficient but working way...*/ |
| 33 | + public int missingNumber(int[] arr) { |
| 34 | + Arrays.sort(arr); |
| 35 | + Map<Integer, List<Integer>> map = new HashMap<>(); |
| 36 | + for (int i = 0; i < arr.length - 1; i++) { |
| 37 | + int diff = arr[i + 1] - arr[i]; |
| 38 | + List<Integer> list = map.getOrDefault(diff, new ArrayList<>()); |
| 39 | + list.add(i); |
| 40 | + map.put(diff, list); |
| 41 | + } |
| 42 | + int smallDiff = arr[arr.length - 1]; |
| 43 | + int bigDiff = 0; |
| 44 | + for (int key : map.keySet()) { |
| 45 | + smallDiff = Math.min(smallDiff, key); |
| 46 | + bigDiff = Math.max(bigDiff, key); |
| 47 | + } |
| 48 | + return arr[map.get(bigDiff).get(0)] + smallDiff; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public static class Solution2 { |
| 53 | + /**credit: https://leetcode.com/problems/missing-number-in-arithmetic-progression/discuss/408474/JavaC%2B%2BPython-Arithmetic-Sum-and-Binary-Search*/ |
| 54 | + public int missingNumber(int[] arr) { |
| 55 | + int min = arr[0]; |
| 56 | + int max = arr[0]; |
| 57 | + int sum = 0; |
| 58 | + for (int num : arr) { |
| 59 | + max = Math.max(max, num); |
| 60 | + min = Math.min(min, num); |
| 61 | + sum += num; |
| 62 | + } |
| 63 | + return (max + min) * (arr.length + 1) / 2 - sum; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments