第一次使用HashMap
来源:互联网 发布:四轴叶轮加工编程方法 编辑:程序博客网 时间:2024/06/06 03:03
题目描述
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
我的代码如下:
import java.util.*;public class twosum { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); String[] A=sc.nextLine().split(" "); int target=sc.nextInt(); int[] num=new int[A.length]; for(int i=0;i<A.length;i++){ num[i]=Integer.parseInt(A[i]); } int[] sum=hashMapTwoSum(num,target); System.out.println(sum[0]+" "+sum[1]); } static int[] hashMapTwoSum(int[] numbers,int target){ int[] sum=new int[2]; HashMap<Integer,Integer>map=new HashMap<Integer,Integer>(); for(int i=0;i<numbers.length;i++){ if(map.containsKey(numbers[i])){ sum[0]=map.get(numbers[i])+1; sum[1]=i+1; } else{ map.put(target-numbers[i], i); } } return sum; }}
0 0
- 第一次使用HashMap
- HashMap使用
- 使用HashMap
- HashMap使用
- HashMap使用
- hashmap 使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- 第一次使用
- UVA11475:Extend to Palindrome(Hash 或 KMP)
- mirrors.163.com yum源
- 关于vlan标签知识的总结
- CSS图片自适应大小
- 直接插入排序
- 第一次使用HashMap
- LWIP使用经验
- 装饰者模式-装饰java.io类
- 【hibernate】基础映射
- Android Studio解决fetching documentation问题——悬浮不能显示文档
- 递归递推练习专题总结
- Commons 组件学习笔记
- 04-树6 Complete Binary Search Tree (30分)
- 折半插入排序