【LeetCode学习】【1:Two Sum】

来源:互联网 发布:cf怎么老是网络异常 编辑:程序博客网 时间:2024/06/06 02:48

题目描述:

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 the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 /// space O(1) , time O(n^2)public class Solution {    public int[] twoSum(int[] nums, int target) {        int[]res = new int[2];        for(int x = 0 ; x<nums.length-1; x++){             for( int y = x+1; y < nums.length; y++){                 if(nums[x]+nums[y]==target){                     res[0]= x;                     res[1]= y;                     break;                 }           }        }  return res;    }}
   /// space O(n) , time O(n)public class Solution {    public int[] twoSum(int[] nums, int target) {        int []res= new int[2];     HashMap<Integer,Integer> checks = new HashMap<Integer,Integer>();        for(int i = 0 ; i < nums.length; i++){        //这说明这个nums[i]和之前放进的nums[i]相加刚好等于target,        //也就是说target- nums[i]是之前放进去的那个nums[i], 那个i和这个i的下标就是所求数组的元素            if(checks.containsKey(target-nums[i])){                res[0] = checks.get(target-nums[i]) ;                res[1] = i;                break;            }else{                checks.put(nums[i], i);            }        }        return res;    }}
原创粉丝点击