(java)leetcode-1

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值