首页 > 其他 > 详细

Codewars Solution:Two Sum

时间:2020-06-04 15:20:56      阅读:35      评论:0      收藏:0      [点我收藏+]

Level 6 kyu :Two Sum

编写一个函数,该函数接受一个数字数组(用于测试的整数)和一个目标数字。

它应该在数组中找到两个不同的项,将它们加在一起后就可以得出目标值。

然后,应在一个元组中返回这些项目的索引,如下所示:(index1, index2)

出于本kata的目的,某些测试可能有多个答案。任何有效的解决方案都将被接受。

输入将始终有效(数字将是长度为2或更大的数组,并且所有项目均为数字;目标将始终是该数组中两个不同项目的总和)。

例如:twoSum [1, 2, 3] 4 === (0, 2)

主要方法:

1、循环

 1 public static int[] twoSum(int[] numbers, int target){
 2     int[] index=new int[2];
 3     for(int i=0;i<numbers.length-1;i++) {
 4         for(int j=i+1;j<numbers.length;j++) {
 5             if(numbers[i]+numbers[j]==target) {
 6                 index[0]=i;
 7                 index[1]=j;
 8             return index;
 9             }
10         }
11     }
12     return null; // Do your magic!
13 }

 

Codewars Solution:Two Sum

原文:https://www.cnblogs.com/mc-web/p/13041686.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!