介绍算法
越往基础和底层学习,就愈加的发现数据结构和算法的魅力,这些曾经在大学时候极为讨厌的两门枯燥乏味的学科,想不到现在也会慢慢的开始喜欢,因此从今天开始试着刷刷Leetcode的题目,虽然上班后的时间并不宽松,但只要像写博文同样,坚持下来,哪怕一天刷一道题,或者几天刷一道题 我相信总有会让人欣慰的收获!sql
对于Leetcode网上已经有不少出色的解题思想和博文,因此我写博客的更多初衷是为了本身养成学习中不断记录的习惯,也但愿在之后忘记的时候能够拿出来翻翻看。shell
Leetcode是国外的一个网站,提供算法、sql、shell性能的题库测试,基本上在国外的大公司都必需要求的门槛,如今算法题总共有343道题目,为了提升自身水平,我也尝试着学习学习,但愿本身愈来愈厉害,哈哈,有兴趣的你们一块儿刷。还能够讨论讨论 交换思路。数组
题目:数据结构
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.性能
Example:学习
Given nums = [2, 7, 11, 15], target = 9,测试
Because nums[0] + nums[1] = 2 + 7 = 9,网站
return [0, 1].
UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully.
解题:new Map<Integer,Integer>(),迭代nums数组元素,检查当前Index元素是否在Map中,若是在返回value与当前Index的数组,若是不在使用target
减去当前元素
,而后把差放到map中(map.put(差,当前Index);
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums==null||nums.length==0)return null;
Map<Integer,Integer> temp=new HashMap<Integer,Integer>();
int[] result=new int[2];
for(int i=0;i<nums.length;i++){
int num=nums[i];
if(temp.containsKey(num)){
result[0]=temp.get(num);
result[1]=i;
return result;
}
int substract= target-num;
temp.put(substract,i);
}
return null;
}
}
复杂度:O(n)的时间,O(n)的内存
测试结果:
思惟发散:大伙能触类旁通的想到其余相似结果吗?
注:版权全部转载请注明出处http://my.oschina.net/ambitor/blog/662408,做者:Ambitor