LeetCode之路——LeetCode_1_TwoSum
来源:互联网 发布:阿里云 国际版 编辑:程序博客网 时间:2024/06/07 01:05
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
解决方案一(39ms):直接两个for循环,直到找到两个数之和为指定值(略)
解决方案二(11ms):用一个类的数组存储数组的元素与对应下标,将其排序,声明一个左索引,初始值为0,一个右索引,初始值为数组长度-1,如果左右索引对应值之和大于目标数,右索引-1,如果小于,左索引+1,直到等于,返回左右索引对应的原数组索引值的数组形式。
public class Solution{
class temp implements Comparable<temp>{ //声明一个类 保存数组的元素以及对应下标,通过Comparable接口实现排序
int index;
int val;
temp(int index,int val){
this.index = index;
this.val = val;
}
public int compareTo(temp o) {
if(this.val < o.val)
return -1;
return 1;
}
}
public int[] twoSum(int[] a,int index){
temp[] T = new temp[a.length];
for(int i =0;i< a.length;i++){ //将数组保存到temp类的数组里
temp t = new temp(i,a[i]);
T[i] = t;
}
Arrays.sort(T); //将temp类的数组排序
int l = 0;
int r = a.length - 1;
while(T[l].val + T[r].val != index){ //比较左右索引对应元素之和(停止循环条件:等于目标数)
if(T[l].val + T[r].val < index) // 如果小了,左索引右移一位
l++;
if(T[l].val + T[r].val > index) //如果大了,右索引左移一位
r--;
}
int[] res = {T[l].index,T[r].index};
return res;
}
}
- LeetCode之路——LeetCode_1_TwoSum
- LeetCode_1_TwoSum(Java Code)
- LeetCode之路——Two Sum
- LeetCode之路——LongestSubstringWithoutRepeatingCharacters
- LeetCode之路——ZigZag Conversion
- LeetCode之路——Reverse Integer
- LeetCode之路——Palindrome Number
- LeetCode之路—— Palindrome Number
- LeetCode之路——3Sum
- LeetCode之路——LeetCode_27_Remove Element
- LeetCode之路——LeetCode_28_Implement strStr()
- LeetCode之路——Add Two Numbers
- LeetCode之路——Median of Two Sorted Arrays
- LeetCode之路——String to Integer (atoi)
- LeetCode之路——Regular Expression Matching
- LeetCode之路——Container With Most Water
- LeetCode之路——Integer to Roman
- LeetCode之路—— Roman to Integer
- 更改svn的登陆账号
- 关于List集合之间求交集,并集,合集,差集等.....
- SQL Server2017 Windows下安装
- RxJava讲解
- jeesite全选 批量删除。有坑啊!
- LeetCode之路——LeetCode_1_TwoSum
- 网易面试小结
- css实现单行、多行文本溢出显示省略号
- sqlite expert 教程
- 爬虫学习备忘
- "设置--安全--未知来源“默认打开
- solr在windows下的安装使用(一)
- 《剑指offer》刷题笔记(时间空间效率的平衡):丑数
- 唯快不破:TCP/IP详解--ICMP 控制报文和差错报文 && Tracerouter 命令的过程