目錄
- 1. 題目
- 2. 解釋
- 3. 思路
- 4. 代碼
- 5. 總結
1. 題目
給定一個數組arr,返回其中的數值的差值等于k的子數組有多少個
2. 解釋
略
3. 思路
直接用hashSet進行存儲,查這個值加上k后的值是否在數組中
4. 代碼
public class Problem01_SubvalueEqualk {public static List<List<Integer>> allPair(int[] arr, int k){HashSet<Integer> set = new HashSet<>();for(int i = 0; i < arr.length; i++){set.add(arr[i]);}List<List<Integer>> ans = new ArrayList<>();for(Integer cur : set){if(set.contains(k + cur)){ans.add(Arrays.asList(cur, k + cur));}}return ans;}public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int k = 5; System.out.println(allPair(arr, k));}
}
輸出結果:
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
5. 總結
so easy!!!