zoukankan      html  css  js  c++  java
  • 523. Continuous Subarray Sum是否有连续和是某数的几倍

    [抄题]:

    Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

    Example 1:

    Input: [23, 2, 4, 6, 7],  k=6
    Output: True
    Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
    

     

    Example 2:

    Input: [23, 2, 6, 4, 7],  k=6
    Output: True
    Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    (a+(n*x))%x is same as (a%x)
    
    For e.g. in case of the array [23,2,6,4,7] the running sum is [23,25,31,35,42] and the remainders are [5,1,1,5,0]. We got remainder 5 at index 0 and at index 3. That means, in between these two indexes we must have added a number which is multiple of the k. Hope this clarifies your doubt :)

    [一句话思路]:

    余数重复,必然增加了几倍

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. pos是之前的index,应该用i - pos是否>1来检测

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [算法思想:递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public boolean checkSubarraySum(int[] nums, int k) {
            //cc
            if (nums == null || nums.length == 0) return false;
            
            //ini: map
            Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,-1);}};;
            int total_sum = 0;
            
            //for loop: get the same sum
            for (int i = 0; i < nums.length; i++) {
                total_sum += nums[i];
                if (k != 0) total_sum %= k;
                Integer pos = map.get(total_sum);
                if (pos != null) {
                    if (i - pos > 1) return true;
                }else {
                    map.put(total_sum, i);
                }
            }
            
            return false;
        }
    }
    View Code

     

  • 相关阅读:
    《基于B_S模式的教务管理系统设计与实现》论文笔记(三)
    《重修补考报名考务管理信息系统中的网络技术》论文笔记(二)
    《基于WEB的独立学院补考重修管理系统研究》论文笔记(一)
    重修安排管理系统的设计与实现 文献收集
    重修安排管理系统的设计与实现 文献收集
    《暗时间》读书笔记
    R、Python、Scala 和 Java,到底该使用哪一种大数据编程语言?
    编程和音乐真的很像吗?
    关于虚拟现实叙事方式的终极入门指南
    如何避免脆弱的代码
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9048843.html
Copyright © 2011-2022 走看看