zoukankan      html  css  js  c++  java
  • [LintCode] Subarray Sum & Subarray Sum II

    Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

    Example

    Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

    用hashmap来存从nums[0]到nums[i]的和以及当前下标i,遍历数组求前缀和acc[i],如果发现acc[i]的值已经在hashmap中的,那么说明已经找到一段子数组和为0了。

     1 class Solution {
     2 public:
     3     /**
     4      * @param nums: A list of integers
     5      * @return: A list of integers includes the index of the first number 
     6      *          and the index of the last number
     7      */
     8     vector<int> subarraySum(vector<int> nums){
     9         // write your code here
    10         map<int, int> has;
    11         int sum = 0;
    12         has[0] = -1;
    13         vector<int> res;
    14         for (int i = 0; i < nums.size(); ++i) {
    15             sum += nums[i];
    16             if (has.find(sum) != has.end()) {
    17                 res.push_back(has[sum] + 1);
    18                 res.push_back(i);
    19                 return res;
    20             } else {
    21                 has[sum] = i;
    22             }
    23         }
    24         return res;
    25     }
    26 };

    Given an integer array, find a subarray where the sum of numbers is between two given interval. Your code should return the number of possible answer.

    Example

    Given [1,2,3,4] and interval = [1,3], return 4. The possible answers are:

    [0, 0]
    [0, 1]
    [1, 1]
    [3, 3]

    先求出前缀和,然后枚举求两个前缀和的差。如果差在start与end之间,就给res+1。注意前缀和数组前要插入一个0。

     1 class Solution {
     2 public:
     3     /**
     4      * @param A an integer array
     5      * @param start an integer
     6      * @param end an integer
     7      * @return the number of possible answer
     8      */
     9     int subarraySumII(vector<int>& A, int start, int end) {
    10         // Write your code here
    11         vector<int> acc(A);
    12         acc.insert(acc.begin(), 0);
    13         for (int i = 1; i < acc.size(); ++i) {
    14             acc[i] += acc[i-1];
    15         }
    16         int tmp, res = 0;
    17         for (int i = 0; i < acc.size() - 1; ++i) {
    18             for (int j = i + 1; j < acc.size(); ++j) {
    19                 tmp = acc[j] - acc[i];
    20                 if (tmp>= start && tmp <= end) ++res;
    21             }
    22         }
    23         return res;
    24     }
    25 };
  • 相关阅读:
    maven安装和配置
    maven的安装和配置
    mac上pydev
    Android自动化----adb shell,appium,uiautomator2
    Django
    centos操作---搭建环境 安装python
    Linux系统centos中sudo命令不能用----提升权限
    python---numpy
    python-socket
    Le x820 的刷机记录
  • 原文地址:https://www.cnblogs.com/easonliu/p/4543647.html
Copyright © 2011-2022 走看看