博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lintcode: Subarray Sum 解题报告
阅读量:7041 次
发布时间:2019-06-28

本文共 1707 字,大约阅读时间需要 5 分钟。

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.

样例

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

标签

SOLUTION 1:

我们有一个O(N)的解法。使用Map 来记录index, sum的值。当遇到两个index的sum相同时,表示从index1+1到index2是一个解。

注意:添加一个index = -1作为虚拟节点。这样我们才可以记录index1 = 0的解。

空间复杂度:O(N)

1 public class Solution { 2     /** 3      * @param nums: A list of integers 4      * @return: A list of integers includes the index of the first number  5      *          and the index of the last number 6      */ 7     public ArrayList
subarraySum(int[] nums) { 8 // write your code here 9 10 int len = nums.length;11 12 ArrayList
ret = new ArrayList
();13 14 HashMap
map = new HashMap
();15 16 // We set the index -1 sum to be 0 to let us more convient to count.17 map.put(0, -1);18 19 int sum = 0;20 for (int i = 0; i < len; i++) {21 sum += nums[i];22 23 if (map.containsKey(sum)) {24 // For example: 25 // -3 1 2 -3 426 // SUM: 0 -3 -2 0 -3 127 // then we got the solution is : 0 - 228 ret.add(map.get(sum) + 1);29 ret.add(i);30 return ret;31 }32 33 // Store the key:value of sum:index.34 map.put(sum, i);35 }36 37 return ret;38 }39 }
View Code

 

GITHUB:

转载地址:http://snxal.baihongyu.com/

你可能感兴趣的文章
24.Silverlight多线程技术BackgroundWorker的应用,更新ProgressBar控件
查看>>
构建高性能ASP.NET站点 第五章—性能调优综述(后篇)
查看>>
Linux自动备份脚本
查看>>
BIND配置文件详解(一)
查看>>
实战Puppet 集中配置管理系统(3)——Puppet dashboard与nginx+passenger安装配置
查看>>
如何让Windows 8/Windows 10用户也用上Docker
查看>>
MySQL Batch Fetch 限制
查看>>
android组件通讯 Intent-Action属性
查看>>
C++ Builder 初学问与答 (九)
查看>>
关闭linux的SElinux的方法
查看>>
【Hibernate框架开发之五】Hibernate对象的三种状态&Session常用方法
查看>>
LINUX ROUTE配置小记
查看>>
如何在 Shell 脚本中执行语法检查调试模式
查看>>
SCVMM2012R2 服务模版系列(四)创建一个开箱即用的Web应用程序服务模版
查看>>
Visual Studio 2010 Ultimate敏捷功能特性(下)
查看>>
为 Neutron 准备物理基础设施(I) - 每天5分钟玩转 OpenStack(75)
查看>>
Android 中文API (91) —— GestureDetector
查看>>
CSS对字体单位的总结
查看>>
统计函数——汇总统计时间类数据
查看>>
精进不休 .NET 4.0 (6) - ADO.NET Data Services 1.5 新特性
查看>>