0
点赞
收藏
分享

微信扫一扫

Java 第 33 课 1282. 用户分组 523. 连续的子数组和



第 33 课

  • [1282. 用户分组](https://leetcode-cn.com/problems/group-the-people-given-the-group-size-they-belong-to/)
  • [523. 连续的子数组和](https://leetcode-cn.com/problems/continuous-subarray-sum/)


1282. 用户分组

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        d = defaultdict(list)
        ans = []
        for i, g in enumerate(groupSizes):
            d[g].append(i)
        for k, v in d.items():
            for i in range(0, len(v), k):
                ans.append(v[i:i+k])
        return ans

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {        
        Map<Integer, List<Integer>> map = new HashMap<>();
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < groupSizes.length; i++){      
            int x = groupSizes[i];
            // if (!map.containsKey(x)) {
            //     map.put(x, new ArrayList<Integer>());                
            // }
            // map.get(x).add(i);

            map.computeIfAbsent(x, key -> new ArrayList<Integer>()).add(i);          
            List<Integer> sub = map.get(x);
            if (sub.size() == x) {
                ans.add(new ArrayList<>(sub));
                sub.clear();
            }
        }
        // for (int k : map.keySet()){
        //     List<Integer> v = map.get(k);
        //     for (int i = 0; i <v.size(); i += k){
        //         ans.add(new ArrayList(v.subList(i, i + k)));
        //     }
        // }
        return ans;
    }
}

523. 连续的子数组和

两个整数 a、b,若它们除以整数 m 所得的余数相等,则称 a 与 b 对于模 m 同余或 a 同余于 b 模 m
记作 a≡b (mod m)
读作 a 同余于 b 模 m,或读作 a 与 b 对模 m 同余。

class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        acc, d = 0, {0:-1}         
        for i, x in enumerate(nums):
            acc += x            
            key = acc % k # 同余
            if key in d:
                if i - d[key] >= 2: return True
            else: d[key] = i  # 保存最小索引        
        return False

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        int acc = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        for (int i = 0; i < nums.length; i++){
            acc += nums[i];
            int rem = acc % k;
            if (map.containsKey(rem)){
                if (i - map.get(rem) >= 2) return true;
            }
            else map.put(rem, i);           
        }
        return false;
    }
}


举报

相关推荐

0 条评论