注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
用JS 刷题,一遇到hash table就各种费劲,又不太懂java。 比如这道,初始化了map {0:0}, 接下来在check map.containsKey(sum), 不会因为已经有sum == 0的情况而直接return ans 吗
还有这道题用js怎么做啊
[color=rgba(0, 0, 0, 0.65)][b]Description[/b]
[color=rgba(0, 0, 0, 0.65)]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. [color=rgba(0, 0, 0, 0.65)][b]Example[/b]
[color=rgba(0, 0, 0, 0.65)]Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
- 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 List<Integer> subarraySum(int[] nums) {
-
- int len = nums.length;
-
- ArrayList<Integer> ans = new ArrayList<Integer>();
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
-
- map.put(0, 0);
-
- int sum = 0;
- for (int i = 0; i < len; i++) {
- sum += nums[i];
- if (map.containsKey(sum)) {
- ans.add(map.get(sum));
- ans.add(i);
- return ans;
- }
-
- map.put(sum, i + 1);
- }
-
- return ans;
- }
- }
复制代码
|