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

  • 相关阅读:
    删除排序链表中的重复元素
    爬楼梯
    Sqrt(x)
    Add Binary
    fremarker导出word list
    url中文参数乱码问题
    取值范围
    动态添加echarts
    格式化数据保留两位小数,输入格式为 :xxx,xx,,,,x,,(x为浮点数)
    使用poi读取Excel文件数据
  • 原文地址:https://www.cnblogs.com/lailailai/p/4802407.html
Copyright © 2011-2022 走看看