【HackerRank】Ice Cream Parlor
Sunny and Johnny together have M dollars which they intend to use at the ice cream parlour. Among N flavors available, they have to choose two distinct flavors whose cost equals M. Given a list of cost of N flavors, output the indices of two items whose sum equals M. The cost of a flavor (ci) will be no more than 10000.
Input Format
The first line of the input contains T, T test cases follow.
Each test case follows the format: The first line contains M. The second line contains the number N. The third line contains N single space separated integers denoting the price of each flavor ci.
Output Format
Output two integers, each of which is a valid index of the flavor. The lower index must be printed first. Indices are indexed from 1 to N.
Constraints
1 ≤ T ≤ 50
2 ≤ M ≤ 10000
2 ≤ N ≤ 10000
1 ≤ ci ≤ 10000
The prices of two items may be same and each test case has a unique solution.
又是一个求数组中两个数和正好是m的问题,类似leetcode中的Two Sum问题。
只是在这个问题中,数组中的数是有可能重复的,所以map中的value要用一个arrayList保存。
另外注意找的时候要保持i比在map中找到的坐标小(如代码26行的判断所示),以免重复。
代码如下:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 int t = in.nextInt(); 7 while(t-- >0){ 8 int m = in.nextInt(); 9 int n = in.nextInt(); 10 int[] prices = new int[n]; 11 HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); 12 13 for(int i = 0;i < n;i++){ 14 prices[i]=in.nextInt(); 15 if(!map.containsKey(prices[i])) 16 map.put(prices[i], new ArrayList<Integer>()); 17 map.get(prices[i]).add(i); 18 } 19 20 for(int i = 0;i < n;i++){ 21 int has = prices[i]; 22 int toFind = m-prices[i]; 23 24 if(map.containsKey(toFind)){ 25 for(int temp:map.get(toFind)){ 26 if(i < temp){ 27 System.out.printf("%d %d",i+1,temp+1); 28 System.out.println(); 29 } 30 } 31 } 32 } 33 } 34 } 35 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了