LeetCode 1 Two Sum 题解

Problem:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

Solution:

O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

Cancel rating
1
2
3
4
5

Average Rating: 4.5 (874 votes)

Is this solution helpful? Read our book to learn more.

题目大意:

给定一个数组和一个目标整数,求在数组中的两个和为目标函数的下标,第一个下标要小于第二个下标(确保有且只有一个结果)

解题思路:

两种方法,一种是暴力破解,找到一个数之后在数组中找target减去这个数的数,时间复杂度O(n^2),效率太低,TLE

第二种方法采用可以经常想到的Hash来解决(本文就是用这种方法),Hash存储与查找

另想到的方法有二叉搜索树和二叉平衡树,B树,不过没有代码实现,不知道对不对。

下面是C语言,C++,Java和Python的解题代码,欢迎批评指正。

Java源代码:

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

C语言源代码(C代码由于自己实现了Map,所以代码比较长):

#include<stdio.h>
#include<stdlib.h>
#define HASH_SIZE 10000
struct node{
	int value;
	int key;
	struct node* next;
};
struct node* data[HASH_SIZE];

int contains(int key){
	int hash = abs(key)%HASH_SIZE;
	struct node* p = data[hash];
	while(p!=NULL){
		if(p->key==key)return 1;
		p=p->next;
	}
	return 0;
}
void put(int key,int value){
	int hash = abs(key)%HASH_SIZE;
	struct node* p = data[hash];
	struct node* s = (struct node*)malloc(sizeof(struct node));
	s->key=key;
	s->value=value;
	s->next=NULL;
	if(p==NULL){
		data[hash] = s;
		return;
	}
	while(p->next!=NULL){
		p=p->next;
	}
	p->next=s;
}
int get(int key){
	int hash = abs(key)%HASH_SIZE;
	struct node* p = data[hash];
	while(p!=NULL){
		if(p->key==key)return p->value;
		p=p->next;
	}
	return 0;
}
int abs(int value){
	return value>0?value:-value;
}
int* twoSum(int* nums, int numsSize, int target) {
	 int* res = (int*)malloc(sizeof(int)*2);
	 int value;
	 for(value=0;value<HASH_SIZE;value++){
	     data[value]=NULL;
	 }
     for(int i=0;i<numsSize;i++){
		 if(contains(target-nums[i])){
			 value = get(target-nums[i]);
			 res[0]=value;
			 res[1]=i+1;
			 return res;
		 }
		 put(nums[i],i+1);
     }
    return res;
}

C++源代码(采用STL的map):

#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> map;
        for(int i=0;i<nums.size();i++){
			std::map<int, int>::iterator iter;
            iter = map.find(target-nums[i]);
            if(iter!=map.end()){
                vector<int> vec;
				vec.push_back(iter->second);
				vec.push_back(i+1);
				return vec;
            }
            map[nums[i]]=i+1;
        }
        return vector<int>();
    }
};

Python源代码(不得不说Python代码量就是少啊,爽):

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[]}
    def twoSum(self, nums, target):
        map={};
        for i in range(0,len(nums)):
            if map.has_key(target-nums[i]):
                return map[target-nums[i]],i+1
            map[nums[i]]=i+1
        return 0,0
时间: 2024-10-10 17:43:36

LeetCode 1 Two Sum 题解的相关文章

LeetCode: Two Sum 题解

Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that

[LeetCode] 039. Combination Sum (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 039. Combination Sum (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 给出一些正整数集合,以及一个目标数,从集合中选择一

[leetcode] 040. Combination Sum II (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 040. Combination Sum II (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum-ii/ 代码(github):https://github.com/illuz/leetcode 题意: 跟 039 一样(给出一些正整数集合,

LeetCode --- 1. Two Sum

题目链接:Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Plea

LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1.题目名称 Range Sum Query(数组指定区间内的元素和) 2.题目地址 https://leetcode.com/problems/range-sum-query-immutable/ 3.题目内容 英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j

【Leetcode】Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 思路:与[Leetcode]Path Sum 不同

LeetCode: Add Two Numbers 题解

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

1.题目名称 Path Sum(树的根节点到叶节点的数字之和) 2.题目地址 https://leetcode.com/problems/path-sum/ 3.题目内容 英文:Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 中文:给定一颗二叉树,如

Java for LeetCode 216 Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascending order. Example 1