zoukankan      html  css  js  c++  java
  • LintCode Subarray Sum

    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.
    Have you met this question in a real interview? Yes
    Example
    Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
    Note
    There is at least one subarray that it's sum equals to zero.

    卡了一会,需要求一个sum = sigma(a[0]..a[i])的累加和,因为如果某个subarray是0的话,就会出现有两个累加和相同的请求。比如上面例子中的累加和:

    -3 -2 0 -3 -1
    

    可以看到有两个-3,也就是说在这两者之间其subarray和为0,才导致了两个位置累加和重叠。还有一种简单的情况就是碰到摸个累加和为0,那么也就是说从数组开始到当前位置的和为0。

    class Solution {
    public:
        /**
         * @param nums: A list of integers
         * @return: A list of integers includes the index of the first number 
         *          and the index of the last number
         */
        vector<int> subarraySum(vector<int> nums){
            // write your code here
            
            int len = nums.size();
            vector<int> res;
     
            int sum = 0;
        
            unordered_map<int, int> val2idx;
            
            for (int i = 0; i < len; i++) {
                sum += nums[i];
                if (sum == 0) {
                    res = {0, i};
                    return res;
                }
                if (val2idx.count(sum) > 0) {
                    res = {val2idx[sum] + 1, i};
                    break;
                }
                val2idx[sum] = i;
            }
            
            return res;
        }
    };
    

    感觉放在easy等级里不合适

  • 相关阅读:
    2015-01-21
    水文分析手册ArcHydro Tool 中文操作手册
    03018_监听器Listener
    元旦去峨眉山吧,人间值得
    常用Oracle SQL集锦
    结合公司现状浅谈CMDB
    CentOS7-Nginx编译安装
    Linux配置C++11编译环境
    Python实现通用web框架
    Python实现通用web框架
  • 原文地址:https://www.cnblogs.com/lailailai/p/4802407.html
Copyright © 2011-2022 走看看