lintcode 之子数组之和

来源:互联网 发布:什么是工业组态软件 编辑:程序博客网 时间:2024/04/28 06:45

题目:

给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置

解答:

同时用一个hash来记录每一个sum对应的下表,只要出现相同的sum,他们之间的这一部

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        if (nums.size() == 0) {            return {};        }        map<int, vector<int>> hash;        hash[0].push_back(-1);//初始化的时候  默认没有数字是0        int sum = 0;        for (int i = 0;i < nums.size(); ++i) {            sum += nums[i];            if (hash[sum].size() == 1) {                return {hash[sum][0] + 1,i};            }            else {                hash[sum].push_back(i);            }        }        return {};    }};

分就一定是和为0的

0 0
原创粉丝点击