博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求两数之和
阅读量:6880 次
发布时间:2019-06-26

本文共 1617 字,大约阅读时间需要 5 分钟。

 

Two Sum

 

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=9

Output: index1=1, index2=2

 

1 package AddTwoNumbers; 2  3 public class addTwoNums { 4  5     public static int[] twoSum(int[] nums, int target) { 6         int[] indexArray = {1,1}; 7         int i = 0; 8         boolean flag = false; 9         while (i < nums.length) {10             for (int j = i + 1; j < nums.length; j++) {11                 if((nums[i] + nums[j]) == target){12                     indexArray[0] = i + 1;13                     indexArray[1] = j + 1;14                     flag = true;15                     break;16                 }17             }18             if (flag == true)19                 break;20             i++;21         }22         23         if(indexArray[0] > indexArray[1]){24             int temp;25             temp = indexArray[0];26             indexArray[0] = indexArray[1];27             indexArray[1] = temp;28         }29         30         return indexArray;31     }32 33     public static void main(String args[]){34         int[] nums = {11,4,3,2,1};35         int[] result = null;36         result = twoSum(nums,6);37         for (int i = 0; i < result.length; i++) {38             System.out.println(result[i]);39         }40     }41 }

 

转载地址:http://etgfl.baihongyu.com/

你可能感兴趣的文章
纪念我曾经的 JAVA 姿势--转
查看>>
js 如何清除setinterval
查看>>
我为NET狂官方面试题-数据库篇答案
查看>>
玩转iOS开发:iOS开发中的装逼技术 - RunTime(一)
查看>>
CSS实现水平垂直居中的1010种方式(史上最全)
查看>>
BCH曼谷矿工会议的积极方面:社区彼此更加了解
查看>>
Android之观察者模式
查看>>
微信公众号支付开发全过程(Java 版)
查看>>
SwiftLint代码规范属性说明(二)
查看>>
本周半价(12.16-12.22)电子书
查看>>
是时候深入了解Linux的系统结构了
查看>>
4月第3周业务风控关注 | 文化部再次审查直播和游戏产品,已下架4939款直播应用...
查看>>
源码探探之startActivity(二)
查看>>
深入了解Flutter的isolate(1) ---- 事件循环(event loop)及代码运行顺序
查看>>
startService() 过程
查看>>
WebSocket 协议 1~4 节
查看>>
Android-WItemTouchHelperPlus几行代码搞定仿QQ侧滑
查看>>
Glide 知识梳理(5) 自定义GlideModule
查看>>
聊聊eureka的delta配置
查看>>
Masonry 源码解读(下)
查看>>