LeetCode TwoSum(两和)
来源:互联网 发布:js 数组方法 indexof 编辑:程序博客网 时间:2024/05/19 13:44
LeetCode 每日一题
****LeetCode 每日一题:
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。
列:给定nums = [2,7,11,15],target = 9,
因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9,
返回[ 0,1 ]。**
public static void main(String[] args) { //int[] num = new int[] {150,24,79,50,88,345,3}; //int[] num = new int[] {3,3}; //int[] num = new int[]{3,2,4}; //int[] num = new int[]{0,1,2,0}; int[] num = new int[] {230,863,916,585,981,404,316,785,88,12,70,435,384,778,887, 755,740,337,86,92,325,422,815,650,920,125,277,336,221,847,168,23,677,61, 400,136,874,363,394,199,863,997,794,587,124,321,212,957,764,173,314,422, 927,783,930,282,306,506,44,926,691,568,68,730,933,737,531,180,414,751,28, 546,60,371,493,370,527,387,43,541,13,457,328,227,652,365,430,803,59,858, 538,427,583,368,375,173,809,896,370,789}; int target = 666; if(num.length < 3) { if(num[0] + num[1] == target) { System.out.print("0 1"); } }else{ int[] twoSum = twoSum(num,target); for (int i = 0; i < twoSum.length ; i++) { if(twoSum[0] == twoSum[1]) { throw new IllegalArgumentException ("No two sum solution"); } System.out.print(twoSum[i]+" "); } } } public static int[] twoSum(int num[],int target) { int temp = num.length; if(num.length > 5) { temp = num.length - 1 ; } int q = 0; int e = 0; for (int i = 0; i < temp ; i++) { for (int j = i+1; j < temp; j++) { //先判断是否等于这个值 if(num[i] + num[j] == target ) { q = num[i]; e = num[j]; } } //找到第一个 继续找下一个 if(num[i] == q) { q = i; continue; } //找到第二个直接中断循环 if(num[i] == e) { e = i; break; } } return new int[] {q,e}; }
大家有没有更好的思路,让程序运行更快一点呢?
阅读全文
0 0
- LeetCode TwoSum(两和)
- [leetcode]-twoSum
- [leetcode]twoSum
- LeetCode-TwoSum
- 【Leetcode】TwoSum
- LeetCode - TwoSum
- leetcode :twoSum
- leetcode TwoSum
- leetcode twosum
- leetcode--twoSum
- LeetCode twoSum
- LeetCode-TwoSum
- leetcode--twoSum
- leetcode TwoSum
- TwoSum leetcode
- leetcode:twosum
- leetcode:TwoSum
- LeetCode---TwoSum
- 如何通过反射调用对象的方法?
- Spark-2.1.1集群的安装和配置(基于Hadoop-2.7.3)
- iPhone X 苹果官方人机交互指南 手动翻译
- 竟然忘记改标题 what a fuk
- Ubuntu 16.04 LTS + CUDA8.0 + cudnn6.0
- LeetCode TwoSum(两和)
- python3.+安装scrapy框架
- 密码学需要了解的一些基础术语和基本知识
- 最大公共子串
- GSON解析泛型错误
- Spring Boot 属性配置和使用
- linux shell if 参数
- gevent
- Windows远程访问Ubuntu桌面