农民代表
- 积分
- 7520
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-11-14
- 最后登录
- 1970-1-1
|
第八题: 用hashmap: time o(n), space o(n)- public class Solution {
- /**
- * @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
- */
- public ArrayList<Integer> subarraySum(int[] nums) {
- // write your code here
- // Store index and sum
- Map<Integer,Integer> map = new HashMap<Integer, Integer>();
- ArrayList<Integer> res = new ArrayList<Integer>();
- int sum = 0;
- map.put(0,-1);
- for (int i=0; i<nums.length; i++) {
- sum +=nums[i];
- if (map.containsKey(sum)) {
- res.add(map.get(sum)+1);
- res.add(i);
- return res;
- }
- else
- map.put(sum, i);
- }
- return res;
- }
- }
复制代码 |
|