-
1387. Sort Integers by The Power ValueAlgorithm/java tip 2021. 3. 21. 00:12
leetcode.com/problems/sort-integers-by-the-power-value/
class Solution { /* even -> x /= 2; odd -> x = 3*x + 1 return step count lo - - - hi sort power value asc same - asc 12, 13, 14, 15 9, 9, 17, 17 13 */ class POW { public int val; public int pow; public POW(int val, int pow) { this.val = val; this.pow = pow; } } public int getKth(int lo, int hi, int k) { POW[] arr = new POW[hi - lo + 1]; for(int i = 0; i < hi - lo + 1; i++) { arr[i] = new POW(lo + i, powerValue(lo + i)); } Arrays.sort(arr, (a, b) -> { if(a.pow == b.pow) { return a.val - b.val; } return a.pow - b.pow; }); return arr[k - 1].val; } public int powerValue(int x) { int cnt = 0; while(x != 1) { if(x % 2 == 0) { x /= 2; } else { x = 3 * x + 1; } cnt++; } return cnt; } }
'Algorithm > java tip' 카테고리의 다른 글
230. Kth Smallest Element in a BST (0) 2021.03.24 198. House Robber (0) 2021.03.23 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20 797. All Paths From Source to Target (0) 2021.03.20 98. Validate Binary Search Tree (0) 2021.03.14