刷题——分糖果
来源:互联网 发布:手机在线网页源码 编辑:程序博客网 时间:2024/06/08 12:38
import java.util.HashMap;/* * 题目描述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=9Output: index1=1, index2=2 */public class TwoSum {//方法一:使用HashMappublic static int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();//(值,对应下标) int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) {map.put(numbers[i], i+1);} for (int i = 0; i < numbers.length; i++) {if (map.containsKey(target-numbers[i]) && map.get(target-numbers[i])!=i+1) {//有对应数且不是自身result[0] = i+1;result[1] = map.get(target-numbers[i]);break;}} return result; }public static void main(String[] args) {// TODO Auto-generated method stubint[] numbers={2, 7, 11, 15};int[] result = twoSum(numbers,9);System.out.println(result[0]+" "+result[1]);}}
阅读全文
0 0
- 刷题——分糖果
- 蓝桥杯—分糖果
- 蓝桥杯——分糖果
- [LeetCode]Candy——分糖果问题
- [LeetCode]—Candy 分糖果问题
- hunnu11543:小明的烦恼——分糖果
- hunnu--11543--小明的烦恼——分糖果
- 2016蓝桥杯历届往题——分糖果
- C++实现——小孩分糖果问题
- 蓝桥杯历届试题——分糖果(模拟)
- 蓝桥杯PREV-32——历届试题 分糖果
- 差分约束——BZOJ2330/Luogu3275 [SCOI2011]糖果
- 【BZOJ2330】【SCOI2011】糖果——差分约束系统+tarjan
- 初见蓝桥—— 历届试题 分糖果
- Codevs2404糖果——差分约束系统整理
- 算法爱好者——分糖果 ? 待解决
- POJ3159—糖果分配 差分约束系统实现
- 第五届蓝桥杯B组Java—分糖果
- 解释器模式--注重的解释的思想
- python字符串处理rstrip()、lstrip()、strip()函数使用
- CSU-ACM2017暑假集训比赛1 C
- 如何获取指定objectName的QObject
- AngularJS 指令对象的Scope属性
- 刷题——分糖果
- 欢迎使用CSDN-markdown编辑器
- 深搜的剪枝
- 堆和栈的区别(转过无数次的文章)
- 剑指Offer——树的子结构
- 电商项目实战——第一天(环境部署)2
- 截获所有以太网帧数据并进行具体分析
- 【github notepad】QT 标签的快速切换、文本特殊格式清除
- Unity 摄像机简介