Algorithm/java tip

1387. Sort Integers by The Power Value

개구리는 개꿀개꿀 2021. 3. 21. 00:12

leetcode.com/problems/sort-integers-by-the-power-value/

 

Sort Integers by The Power Value - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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;
    }
}

leetcode.com/problems/sort-integers-by-the-power-value/discuss/546526/Java-Simple-Bottom-up-DP-approach-or-Easy

 

[Java] Simple Bottom up DP approach | Easy - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com