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

    Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
    Have you met this question in a real interview? Yes
    Example
    Given [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4]
    Challenge
    O(nlogn) time

    这个和前面一个subarray sum的题目有些类似,也是先求出累计和,然后再对他们排序,相近的累计和总是相邻的,于是可以得到最靠近的0的subarray 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> subarraySumClosest(vector<int> nums){
            // write your code here
            int len = nums.size();
            vector<int> res;
            vector<pair<int, int>> sums;
            int sum = 0;
            for (int i = 0; i < len; i++) {
                sum += nums[i];
                sums.push_back({sum, i});
                if (sum == 0) {
                    res = {0, i};
                    return res;
                }
            }
            
            sort(sums.begin(), sums.end());
            
            int diff = abs(sums[0].first);
            res = {0, 0};
            
            for (int i = 1; i < len; i++) {
                auto& prev = sums[i - 1];
                auto& curr = sums[i];
                int cdiff = abs(prev.first - curr.first);
                if (cdiff < diff) {
                    diff = cdiff;
                    if (prev.second < curr.second) {        
                        res = {prev.second + 1, curr.second};
                    } else {
                        res = {curr.second + 1, prev.second};
                    }
                }
            }
            
            return res;
        }
    };
    
    
    
  • 相关阅读:
    oracle RAC 更换IP
    12C oracle 12.1.0.2版本打补丁
    node name配置错误,导致grid日志在报警
    input_subsys 输入子系统框架分析
    www.bing.com
    getopt函数使用说明
    FreeType 矢量字体 测试移植(1)
    字符的编码方式
    在开发板上显示字符和中文
    块设备驱动程序的框架
  • 原文地址:https://www.cnblogs.com/lailailai/p/4803754.html
Copyright © 2011-2022 走看看