首页 > 试题广场 >

糖果

[编程题]糖果
  • 热度指数:269 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给你一个数组 candies 和一个整数 candiesNeed ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目,编写一个函数求是否存在两个孩子的糖果数之和等于candiesNeed ,并输出两个孩子的编号。
注意:若存在多种组合,则输出下标较小的。例如满足条件的孩子有0和1、0和2,则输出0和1;满足条件的孩子有0和3、1和2,则输出0和3。
示例1

输入

1,[1,0,1,2]

输出

[0,1]
示例2

输入

1,[0,1,2,3]

输出

[0,1]
示例3

输入

1,[2,3,4,3]

输出

[-1,-1]
 hashmap = dict()
        for i, num in enumerate(candiesNeed):
            if candies - num in hashmap:
                return [hashmap[candies - num], i]
            hashmap[candiesNeed[i]] = i
        return [-1,-1]


发表于 2022-09-19 18:05:28 回复(0)
java:
public class Solution {
    public int[] find_children (int candiesNeed, int[] candies) {
        // write code here
        for(int i=0;i<candies.length;i++){
            for(int j =i+1;j<candies.length;j++){
                if(candies[i]+candies[j]==candiesNeed){
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{-1,-1};
    }
}
发表于 2022-09-01 18:13:35 回复(0)
[Python3] 不要想复杂了,直接嵌套遍历!
class Solution:
    def find_children(self , candiesNeed , candies ):
        for i in range(len(candies)):
            for j in range(i+1, len(candies)):
                if candies[i] + candies[j] == candiesNeed:
                    return [i, j]
        return [-1, -1]


发表于 2021-07-29 22:23:36 回复(0)