作者:melodyhaoduo | 来源:互联网 | 2024-10-25 11:52
图片中的方法仅为个人理解,欢迎各位在下方评论packagecom.shengda.Demo0Likou;importjava.util.HashMap;impor
图片中的方法仅为个人理解,欢迎各位在下方评论
package com.shengda.Demo0Likou;import java.util.HashMap;
import java.util.Map;public class Demo1 {public static void main(String[] args) {Solution s = new Solution();int[] nums = {3,3};int[] num = s.twoSum(nums,6);for (int i = 0; i < num.length; i++) {System.out.println(num[i]);}}
}class Solution {public int[] twoSum(int[] nums,int target){Map<Integer,Integer> map = new HashMap<>();int[] num = new int[2];for (int i = 0; i < nums.length; i++) {int data = target-nums[i];if(map.containsKey(data)){ num[0] = map.get(data); num[1] = i; return num;}map.put(nums[i],i); }return num;}
}