《漫画算法2》源码整理-6 两数之和 三数之和
生活随笔
收集整理的這篇文章主要介紹了
《漫画算法2》源码整理-6 两数之和 三数之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
兩數之和
import java.util.*;public class TwoSum {public static List<List<Integer>> twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();List<List<Integer>> resultList = new ArrayList<>();for (int i = 1; i < nums.length; i++) {map.put(nums[i], i);}for (int i = 0; i < nums.length; i++) {int d = target - nums[i];if (map.containsKey(d) && map.get(d) != i) {resultList.add(Arrays.asList(nums[i], d));//為防止找到重復的元素對,匹配后從哈希表刪除對應元素map.remove(nums[i]);}}return resultList;}public static List<List<Integer>> twoSumV2(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();List<List<Integer>> resultList = new ArrayList<>();for (int i = 0; i < nums.length; i++) {int d = target - nums[i];if (map.containsKey(d)) {resultList.add(Arrays.asList(nums[i], d));}map.put(nums[i], i);}return resultList;}public static void main(String[] args) {int[] nums = {5,12,6,3,9,2,1,7};List<List<Integer>> resultList = twoSumV2(nums, 12);for(List<Integer> list : resultList){System.out.println(Arrays.toString(list.toArray()));}}}三數之和
import java.util.*;public class ThreeSum {public static List<List<Integer>> threeSum(int[] nums, int target) {List<List<Integer>> resultList = new ArrayList<>();for (int i = 0; i < nums.length; i++) {Map<Integer, Integer> map = new HashMap<>();int d1 = target - nums[i];//尋找兩數之和等于d1的組合for (int j = i+1; j < nums.length; j++) {int d2 = d1 - nums[j];if (map.containsKey(d2)) {resultList.add(Arrays.asList(nums[i], d2, nums[j]));}map.put(nums[j], j);}}return resultList;}public static List<List<Integer>> threeSumv2(int[] nums, int target) {Arrays.sort(nums);List<List<Integer>> resultList = new ArrayList<List<Integer>>();//大循環for (int i = 0; i < nums.length; i++) {int d = target - nums[i];// j和k雙指針循環定位,j在左端,k在右端for (int j=i+1,k=nums.length-1; j<nums.length; j++) {// k指針向左移動while (j<k && (nums[j]+nums[k])>d) {k--;}//雙指針重合,跳出本次循環if (j == k) {break;}if (nums[j] + nums[k] == d) {List<Integer> list = Arrays.asList(nums[i], nums[j], nums[k]);resultList.add(list);}}}return resultList;}public static void main(String[] args) {int[] nums = {5,12,6,3,9,2,1,7};List<List<Integer>> resultList = threeSumv2(nums, 12);for(List<Integer> list : resultList){System.out.println(Arrays.toString(list.toArray()));}}}總結
以上是生活随笔為你收集整理的《漫画算法2》源码整理-6 两数之和 三数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《漫画算法2》源码整理-5 二维数组螺旋
- 下一篇: 《漫画算法2》源码整理-7 第K大的数字