gpt4 book ai didi

java - 查找价格加起来等于数组中某个值的两个商品的索引

转载 作者:行者123 更新时间:2023-11-30 02:42:03 24 4
gpt4 key购买 nike

我正在尝试解决 Google Code jam 问题。

Problem

You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).

Input

The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:

One line containing the value C, the amount of credit you have at the store. One line containing the value I, the number of items in the store. One line containing a space separated list of I integers. Each integer P indicates the price of an item in the store. Each test case will have exactly one solution. Output

For each test case, output one line containing "Case #x: " followed by the indices of the two items whose price adds up to the store credit. The lower index should be output first.

到目前为止我已经这样做了。但是,当我将 100 , 3 , 5 , 75 , 25 作为输入时,我得到 1,22,1 作为输出,因为它第二次迭代数组。如何获得 1,2 作为输出?

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int credit = in.nextInt();

int number = in.nextInt();

int[] items = new int[number];
for (int i = 0; i < number; i++){
items[i] = in.nextInt();
}

for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (items[i] + items[j] == credit){
System.out.print(i + "," + j + " ");
}
}
}
}
}

最佳答案

您应该让内部循环仅从 j=i+1 开始:

for (int i = 0; i < number - 1; i++){
for (int j = i + 1; j < number; j++){
if (items[i] + items[j] == credit){
System.out.print(i + "," + j + " ");
}
}
}

关于java - 查找价格加起来等于数组中某个值的两个商品的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com