zoukankan      html  css  js  c++  java
  • LintCode-子数组之和

    题目描述:

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

    样例

      给出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].

     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<Integer> subarraySum(int[] nums) {
     8       ArrayList<Integer> pos = new ArrayList<Integer>();
     9      if(nums.length==1 && nums[0]==0){
    10          pos.add(0);
    11          pos.add(0);
    12          return pos;
    13      }
    14      int[] preSum = new int[nums.length];
    15      int t=0;
    16      for(int i=1;i<nums.length+1;i++){
    17          Integer sum = 0;
    18          for(int j=0;j<i;j++){
    19              sum += nums[j];
    20          }
    21          if(sum==0){
    22              pos.add(0);
    23              pos.add(i-1);
    24              return pos;
    25          }
    26          for(int k=0;k<preSum.length;k++){
    27              if(preSum[k]==sum){
    28                  pos.add(k+1);
    29                  pos.add(i-1);
    30                  return pos;
    31              }
    32          }
    33          preSum[t++] = sum;
    34      }
    35      return pos;
    36     }
    37 }
  • 相关阅读:
    浅谈前端的CSS
    浅谈前端的HTML
    python操作mysql
    简单的sql题目和解答
    子查询&视图&事务
    测试程序运行的时间
    API接口简单的写法
    数据库数据进行量化算法入库
    正则爬取二手房数据
    接口加密和破解
  • 原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5364632.html
Copyright © 2011-2022 走看看