LeetCode第一题:Two Sum

Two Sum 题目简述

题目链接:https://leetcode.com/problems/two-sum/?tab=Description

题目原文:

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].

题目大意:

给定一个整型数组nums[]和一个整型数target,编写程序在nums数组中找出两个元素 a ,b ,使 a + b = target 。返回 a 和 b 在nums中的数组下标。

解法一:直接遍历,复杂的O(N^2)

思路:直接使用两层循环遍历数组,判断给定数组中任意两个元素之和是否与给定整型数target相等。

代码(C语言):
int* twoSum(int* nums, int numsSize, int target) {
    int* indices = (int*)malloc(2*sizeof(int));
	for (int i = 0; i<numsSize; i++) {
		for (int j = i + 1; j< numsSize; j++) {
			if (*(nums + i) + *(nums + j) == target) {
				indices[0] = i;
				indices[1] = j;
				return indices;
			}
		}
	}
	return indices;
}

解法二:哈希表法,复杂的O(N)

思路:

题目其实就是要在数组中查找一个与数组某元素之和等于target的数。所以本质上是一个查找问题!提高查找效率的基本方法就是二分查找法和哈希表法,二分查找需要序列有序,在此题中显然不宜。因此自然想到要用hash表法解决此题。

我们只需要遍历数组,对遍历到的元素nums[i],判断 target - nums[i]是否在哈希表中存在。如果不存在就将nums[i]加入哈希表。如果存在则说明哈希表中存在对应元素,与nums[i]之和为target。返回 i 与 哈希表中元素对应的数组下标即可。

由于hash查找的时间复杂度为O(1),故整个程序时间复杂度为O(n)。


代码(java):

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] indices = new int[2];
        int sub;
        for (int i=0 ; i < nums.length ; i++){
            sub = target - nums[i];
            if(map.containsKey(sub)){
                indices[0] = map.get(sub);
                indices[1] = i;
                return indices;
            }
            map.put(nums[i] , i);
        }
        return indices;
    }
}





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值