2.29

1 到达终点

https://leetcode-cn.com/problems/reaching-points/

 

 

 思路:暴力去做的话 无论是dfs或者bfs 从sx,sy到tx,ty去搜索 都会产生很多无效的状态 最后造成超时。通过题目发现 tx和ty中最大的那个数 肯定是由最小的那个数相加得来的,那么我们可以从tx,ty来反推 看一下是否可以变为sx,sy 。而我们发现 每次减去一个数之后如果还是比另一个数大 那么我们还需要减去一次 这样我们可以通过取模 一次算出结果。循环结束后,如果 tx < sx 或者 ty < sy,则不可能到达;如果 tx == sx,则我们判断 ty 与 sy 的差值是否能由 sx 拼凑而成;同理,如果 ty == sy,则我们判断 tx 与 sx 的差值是否能由 sy 拼成。

java和c++代码如下:

class Solution {
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
    while(sx<tx&&sy<ty){
           if(tx>ty) tx %= ty;
           else ty %= tx;
       }
       if(tx<sx||ty<sy) return false;
       if(tx==sx) return (ty-sy)%tx==0;
       return (tx-sx)%ty==0;
    }
}
class Solution {
public:
    bool reachingPoints(int sx, int sy, int tx, int ty) {
        while (tx > sx && ty > sy) {
            if (tx < ty) ty %= tx;
            else tx %= ty;
        }

        if (tx < sx || ty < sy)
            return false;

        if (sx == tx)
            return (ty - sy) % sx == 0;

        return (tx - sx) % sy == 0;
    }
};

2 森林中兔子的数量

https://leetcode-cn.com/problems/rabbits-in-forest/

 

 思路:如果兔子同一种颜色 那么他们说的数字x必然一样且这种颜色必然有x+1只兔子 我们统计每个数字出现的次数 如果数字x出现的次数是cnt

   1 如果cnt%(x+1)==0 那么一共有cnt/(x+1)种颜色 恰好有cnt只兔子说了x  

   2 如果cnt%(x+1)!=0 那么一共有cnt/(x+1)+1种颜色 有(cnt/(x+1)+1)*(x+1)只兔子 有cnt只兔子说了x 有(cnt/(x+1)+1)*(x+1)-cnt只兔子没有被问到

java和c++代码:

class Solution {
    public int numRabbits(int[] answers) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(Integer u:answers){
            if(map.containsKey(u)) map.put(u, map.get(u)+1);
            else map.put(u,1);
        }
        int res = 0;
        Set<Integer> integers = map.keySet();
        for(Integer u:integers){
            int cnt = map.get(u);
            if(cnt%(u+1)==0) res += cnt;
            else res += (cnt/(u+1)+1)*(u+1);
        }
        return res;
    }
}

 

class Solution {
public:
    int numRabbits(vector<int>& answers) {
        unordered_map<int, int> seen;
        for (int x : answers)
            seen[x]++;

        int tot = 0;
        for (const auto &it : seen) {
            int x = it.first, num = it.second;
            if (num % (x + 1) == 0) tot += num;
            else tot += (num / (x + 1) + 1) * (x + 1);
        }
        return tot;
    }
};

 

posted @ 2021-03-29 17:43  键盘_书生  阅读(61)  评论(0编辑  收藏  举报