(java)leetcode-1

来源:互联网 发布:分支界限算法 编辑:程序博客网 时间:2024/06/05 04:32

Two Sum

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:

Gevin nums = [2,7,11,15],target = 9,

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

return [0,1].


这道题比较简单的一点就是有且只有一组值能够满足,所以不用考虑太多的情况。(一开始想多了...)

解题思路:

1. 暴力求解

直接对数组进行遍历,对于数组中的每一个元素,查找数组后面的元素中是否有满足条件的,有就直接返回。比较粗暴。时间复杂度是o(n^2),空间复杂度是o(1)

public class Solution {    public int[] twoSum(int[] nums, int target)     {        int len = nums.length;        int[] answer = new int[2];        for(int i = 0;i<len;i++)        {            int another = target - nums[i];            for(int j = i+1;j<len;j++)            {                if(nums[j] == another)                {                    answer[0] = i;                    answer[1] = j;                    return answer;                }            }        }        return answer;    }}

2.使用HashMap

用HashMap来存储一对数据<数值,位置>,从前向后遍历,用target减去元素值得到目标值,查找HashMap中是否有与目标值相同的Key,满足则返回结果。时间复杂度o(n),空间复杂度o(n)

import java.util.HashMap;public class Solution {    public int[] twoSum(int[] nums, int target)     {        int len = nums.length;int[] answer = new int[2];HashMap<Integer,Integer> trace = new HashMap<Integer,Integer>();for(int i = 0;i<len;i++){int another = target - nums[i];if(trace.containsKey(another)){answer[0] = trace.get(another);answer[1] = i;break;}trace.put(nums[i], i);}return answer;    }}





0 0
原创粉丝点击