• 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等级里不合适

  • 相关阅读:
    gulp编译sass
    Material Design学习
    js爬虫心得
    js爬虫
    angularjs
    sass心得
    矩阵与线性代数学习笔记
    2-SAT学习笔记
    一个有趣的题目【二分答案,2-SAT,线段树优化】
    vijos训练之——星辰大海中闪烁的趣题
  • 原文地址:https://www.cnblogs.com/lailailai/p/4802407.html
Copyright © 2020-2023  润新知