yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

356. Line Reflection #276

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    public boolean isReflected(int[][] points) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        HashSet<String> set = new HashSet<>();
        for (int[] p : points) {
            max = Math.max(max, p[0]);
            min = Math.min(min, p[0]);
            String str = p[0] + "a" + p[1];
            set.add(str);
        }
        int sum = max + min;
        for (int[] p : points) {
            String str = (sum - p[0]) + "a" + p[1];
            if (!set.contains(str)) return false;
        }

        return true;
    }
}

With Hash Table:

class Solution {
    public boolean isReflected(int[][] points) {
        HashMap<Integer, ArrayList<Double>> map = new HashMap<>();
        double average = 0;
        int count = 0;
        if (points == null || points.length == 0 || points[0].length == 0) return true;

        for (int i = 0; i < points.length; i++) {
            ArrayList<Double> ls = map.get(points[i][1]);
            if (ls == null) ls = new ArrayList<>();
            if (ls.contains((double)points[i][0])) continue;
            ls.add((double)points[i][0]);
            map.put(points[i][1], ls);
            average += points[i][0];
            count++;
        }

        average /= count;

        for (ArrayList<Double> ls: map.values()) {
            int size = ls.size();
            for (int i = 0; i < size; i++) {
                if (ls.get(i) == average) continue;
                double find = 2 * average - ls.get(i);
                if (!ls.contains(find)) return false;
            }
        }
        return true;
    }
}