-
Tip2(easy)Algorithm/java tip 2020. 4. 13. 15:12
문제 : https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
public int[] sortByBits(int[] arr) { // 2진수로 1의 갯수로 오름차순 정렬 // 똑같으면 그냥 오름차순 Data[] data = new Data[arr.length]; for(int i=0; i<arr.length; i++) { String bn = Integer.toBinaryString(arr[i]); data[i] = new Data(arr[i], bn, getOneNum(bn)); } Arrays.sort(data); return Arrays.stream(data).map(e -> e.n).mapToInt(e -> e).toArray(); } class Data implements Comparable<Data> { public Data(int n, String bn, int cnt) { this.n = n; this.bn = bn; this.cnt = cnt; } int n; String bn; int cnt; @Override public int compareTo(Data o) { if(this.cnt == o.cnt) { return this.n - o.n; } return this.cnt - o.cnt; } } private int getOneNum(String bn) { int n=0; for(char c : bn.toCharArray()) { if(c == '1') n++; } return n; }
Comparable을 잘 사용하면 편하다
문제 : https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
참고 : https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/521929/Beats-100-runtimespace
public int[] kWeakestRows(int[][] mat, int k) { //row 별 1의 갯수 오름차순, 갯수가 같다면 index 오름차순 Power[] powers = new Power[mat.length]; for(int i=0; i<mat.length; i++) { int power = 0; for(int j=0; j<mat[i].length; j++) { if(mat[i][j] == 1) { power++; } else { break; } } powers[i] = new Power(power, i); } Arrays.sort(powers); return Arrays.stream(powers).map(e -> e.index).limit(k).mapToInt(e -> e).toArray(); } class Power implements Comparable<Power> { int power; int index; public Power(int power, int index) { this.power = power; this.index = index; } @Override public int compareTo(Power o) { if(this.power == o.power) { return this.index - o.index; } return this.power - o.power; } }
비슷한 문제
문제 : https://leetcode.com/problems/middle-of-the-linked-list/
참고 : https://leetcode.com/problems/middle-of-the-linked-list/discuss/571951/Java-O(n)-solution-fast-and-slow-pointer// 1 -> 2 -> 3 -> 4 -> 5 // 1 -> 2 -> 3 -> 4 -> 5 -> 6 public ListNode middleNode(ListNode head) { int size = 1; ListNode next = head; while(next.next != null) { size++; next = next.next; } int index = 0; next = head; while(index++ < (size / 2)) { next = next.next; } return next; }
'Algorithm > java tip' 카테고리의 다른 글
46. Permutations (0) 2021.03.03 86. Partition List (0) 2021.03.03 Tip4 (0) 2020.04.19 Tip3(Easy) (0) 2020.04.14 Tip1(easy) (0) 2020.04.05