Subarray Sum Closest | LintCode

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

Example

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

Challenge

O(nlogn) time

思路:

发现要求nlogn之后,自然想到了排序;又看到了subarray sum,于是想到了哈希表求subarray O(n)的方法;于是想到了如下方法:

1.遍历数组,用哈希表hash[i]来记录,从0到第i个元素之和。O(n)

2.将哈希表根据value排序。O(nlogn)

3.遍历哈希表,对比相邻两个键值对的value之差,找出相差最小的两个元素,取出他们的key,即是答案


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> subarraySumClosest(vector<int> nums){
        // write your code here
        vector<int> result;
        unordered_map<int,int> mp;
        vector<unordered_map<int, int>::iterator> vec;
        int sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            mp[i] = sum;
        }

        for (auto i = mp.begin();i != mp.end(); i++) {
            vec.push_back(i);
        }
        
        sort(vec.begin(),vec.end(),cmp);
        int mi = INT_MAX;
        int res1 = 0,res2 = 0;
        for (int i = 0; i < vec.size()-1; i++) {
            int sum = abs(vec[i+1]->second - vec[i]->second);
            if (sum < mi) {
                mi = sum;
                res1 = min(vec[i]->first,vec[i+1]->first);
                res2 = max(vec[i]->first,vec[i+1]->first);
            }
        }
        
        if (res1 != res2) {
            res1++;
        }
        result.push_back(res1);
        result.push_back(res2);
        return result;
    }
    static bool cmp(unordered_map<int,int>::iterator start,unordered_map<int,int>::iterator end) {
        if (start->second <= end ->second) {
            return true;
        }
        return false;
    }
};


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值