leetcode刷题(猜数字游戏、数组和计算)

题目一描述:
猜数字游戏(Bulls and Cows)游戏,该游戏规则如下:

1.你写出一个秘密数字,并请朋友猜这个数字是多少
2.朋友每次猜测后,就给他提示,多少个位置是对的,多少个数字存在位置不对
3.知道朋友猜中为止

例如:

secret = “1807” ,guess = “7801”
输出:“1A3B”
1个位置相同,三个元素存在但不相同

题目一分析:
对两个字符串进行遍历,相同位置元素也相同时,将局部变量same++,将相同位置不同的元素中的scret元素加入到一个map中,value是其第几次出现,第二次循环遍历时,将不同位置的元素判断其是否在map中出现,出现时将dif变量++。

例如:“1807” “7801”
i=0,将map中存放1,1
i=1,将same++;
i=2,将map中放入0,1
i=3,将map中放入7,1
第二次遍历时,计算不同位置的元素是否出现过

代码如下:

class Solution {
    public String getHint(String secret, String guess) {
        int same = 0;
        int dif = 0;
        Map<Character,Integer> map = new HashMap();
        for(int i=0;i<secret.length();i++){
        //去当前位置的两个字符串的元素,相同时,same++
           char c = secret.charAt(i);
           char g = guess.charAt(i);
           if(c==g)same++;
           else if(c!=g&&map.containsKey(c)){
              map.put(c, map.get(c)+1);
           }else if(c!=g){
               map.put(c,1);
           }
        }
        //第二次遍历,不同元素的记录
        for(int i=0;i<guess.length();i++){
            char temp = guess.charAt(i);
            if(map.containsKey(temp)&&secret.charAt(i)!=temp){
                if(map.get(temp)>0) dif++;
                //出现时,需要将value--,避免多次判断同一个值
                map.put(temp, map.get(temp)-1);
            }
        }
        return same+"A"+dif+"B";
    }
}

题目二描述:
给定一个整数数组nums,求出数组从索引i到索引j范围内元素的总和,包含i,j两个点。
题目二分析:
对于这样的题目,个人就认为是从i到j位置求和,蛮简单的,当然采用这样的方法求解是可以通过用例测试的,但是每次调用求和方法时都会进行遍历计算,时间复杂度挺高。
针对这样的题型,需要利用好构造函数,将数组从开始到结束所有的和都对应记录下来,最后返回结果进行O(1)的时间做差即可。
例如:

nums = {2,3,6,5,4}
array = {0,2,5,11,16,20}
i=0,j=2时,11-0=11(2,3,6)

代码如下:

class NumArray {
    int[] array = null;
    public NumArray(int[] nums) {
        array = nums;
    }
    //每次进行遍历,得到i到j的和
    public int sumRange(int i, int j) {
        int sum = 0;
        for(int k = i;k<=j;k++){
            sum += array[k];
        }
        return sum;
    }
}

优化程序,利用缓存将数据记录

class NumArray {
    int[] array ;
    //利用构造函数将每个元素前面的累加和记录下来进行缓存
    public NumArray(int[] nums) {
        array = new int[nums.length+1];
       for(int i=0;i<nums.length;i++){
           array[i+1] = nums[i]+array[i];
       }
    }
    
    public int sumRange(int i, int j) {
        if(j<i)return 0;
       return array[j+1] -  array[i];
    }
}

你可能感兴趣的:(复习时使用)