美文网首页
Java日记2018-05-17

Java日记2018-05-17

作者: hayes0420 | 来源:发表于2018-05-17 06:51 被阅读0次

第一题 丑数
把只包含因子 2、3 和 5 的数称作丑数(Ugly Number)。例如 6、8 都是丑数,但 14 不是,因为它包含因子 7。 习惯上我们把 1 当做是第一个丑数。求按从小到大的顺序的第 N 个丑数。

默认把第一个丑数算成1;以第7个丑数为例,一定是前6个丑数乘以2 3 5中最小的。具体来看丑数是1 2 3 4 5 6 8 9。。很显然9是uglyarray[2]3得到的,4是uglyarray[1]2。假设当前丑数是uglyarray[i],那么uglyarray[i+1] 一定是上一个2的因子乘以2,3的因子乘以3,5的因子乘以5中的最小的。那么各因子的索引也一定是小于等于uglyarray[i],下一个索引就自然加1

public static int getugly(int n) {
        if(n<1) return 0;
        int[] uarr = new int[n];
        int index2=0;
        int index3=0;
        int index5=0;
        uarr[0]=1;
        int min=0;
        for(int i=1;i<n;i++) {
            min=min(uarr[index2]*2,uarr[index3]*3,uarr[index5]*5);
            uarr[i]=min;
            while(uarr[index2]*2<=uarr[i]) index2++;
            while(uarr[index3]*3<=uarr[i])  index3++;
            while(uarr[index5]*5<=uarr[i])  index5++;
        }
        return uarr[n-1];
    }
    public static int min(int a,int b,int c){
        int temp = a>b?b:a;
        return temp>c?c:temp;
    }

第二题 第一个只出现一次的字符位置
这个问题很直观,找到hashmap容器,有重复字就+1,然后从容器中取value是1的,没有则返回空

public static Character firstfind(String str) {
        if(str.length()==0) return null;
        HashMap<Character,Integer> hash = new HashMap<>();
        
        for(int i=0;i<str.length();i++){
            if(hash.containsKey(str.charAt(i))) {
                hash.put(str.charAt(i), hash.get(str.charAt(i))+1);
            } else {
                hash.put(str.charAt(i), 1);
            }
        }
        
        for(char key:hash.keySet())  
        {  
            if(hash.get(key)== 1)  
                return key;  
        }  
        return null;
        
    }

相关文章

网友评论

      本文标题:Java日记2018-05-17

      本文链接:https://www.haomeiwen.com/subject/ftuvdftx.html