zoukankan      html  css  js  c++  java
  • 869. 重新排序得到 2 的幂

    回溯

        static Set<Integer> set=new HashSet<>();
        static{
            for(int i=1;i<=(int)1e9;i*=2) set.add(i);
        }
        private int[] cnt=new int[10];
        private int len;
        private boolean dfs(int cur,int pos){
            if(pos==len) return set.contains(cur);
            for(int i=0;i<10;++i){
                if(cnt[i]>0){
                    cnt[i]--;
                    if((cur!=0||i!=0)&&dfs(cur*10+i,pos+1)) return true;
                    cnt[i]++;
                }
            }
            return false;
        }
        public boolean reorderedPowerOf2(int n) {
            while(n!=0){
                cnt[n%10]++;
                n/=10;
                len++;
            }
            return dfs(0,0);
        }
    

    统计数字频次

    预先计算出每个2的幂的各个数字的频次。给定n,若存在某个2的幂的频次分布和n相同则返回true。

        static Map<Integer,int[]> map=new HashMap<>();
        static{
            for(int i=1;i<=(int)1e9;i*=2) {
                int[] cnt=new int[10];
                int n=i;
                while(n!=0){
                    cnt[n%10]++;
                    n/=10;
                }
                map.put(i,cnt);
            }
        }
        public boolean reorderedPowerOf2(int n) {
            int[] cnt=new int[10];
            while(n!=0){
                cnt[n%10]++;
                n/=10;
            }
            for(Integer num:map.keySet()){
                if(Arrays.equals(cnt,map.get(num))) return true;
            }
            return false;
        }
    

    总结

    这道题预处理步骤是提升效率的关键。

  • 相关阅读:
    sentinel.conf样例
    哨兵模式java实例
    哨兵模式启动redis
    华为笔试:直角三角形个数
    leetcode 337. 打家劫舍iii
    leetcode 494. 目标数
    leetcode 394. 字符串解码
    leetcode 128. 最长连续子序列
    链表快排
    leetcode 877. 石子游戏
  • 原文地址:https://www.cnblogs.com/Frank-Hong/p/15475129.html
Copyright © 2011-2022 走看看