Leetcode系列(双语)——GO两数之和

文章目录

  • 两数之和 (Two Sum)
  • 解题
  • 拓展——Solution
    • Solution 1: Brute Force
    • Code
      • Language: Go

两数之和 (Two Sum)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

You may assume that each input would have exactly one solution, and you may not use the same element twice.
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

You can return the answer in any order.
你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

解题

func twoSum(nums []int, target int) []int {
    myMap := make(map[int]int)
    for i, num := range nums {
        if j, ok := myMap[target-num]; ok {
            return []int{j, i}
        }
        myMap[num] = i
    }
    return nil
}

拓展——Solution

Let us try to understand the problem statement first.
Here we are given an array of integer elements and a target sum.
Our job is to write an algorithm which returns indices of two elements in this array such that, when we add these two elements it should be equal to the target sum given.

For instance, in example 1 [7,2,13,11] is the given array and the given target sum = 9.
If we take a look at the given array, the pair which adds to the target sum 9 is (7,2) i.e. 7+2 = 9.
So our algorithm should return (0,1) as the result because these are the indexes of elements 7 and 2 respectively in the given array.

Similarly for the array in example 2 [7,3,5] output is (1,2) because these are the indexes of elements 3 and 5 respectively which add up to the target sum 8.

Note: If there are multiple such pairs we need to return the indexes of first pair we find from left.

It is stated in the problem statement that we can return the indices in any order, what does this mean?
Let us understand this with example 1.
The output for this example is [0,1], so when the problem statement says we can return the indices in any order what it means is that we can return either [0,1] or [1,0] as our output, both will be considered correct.
Same for example 2, we can return either [1,2] or [2,1].

Solution 1: Brute Force

A straight forward solution to this problem is to check for every possible pair present in the given array.

For a given input array nums we need to do the following steps:

  1. Run two loops and check for every combination in the given array.
  2. Fix the outer loop at a specific index and move the inner loop to get all the possible pairs. The outer loop runs from i=0 to i=n-2 and inner loop runs from j=i+1 to j=n-1.
  3. In each iteration of the inner loop check if the numbers represented by the outer and inner loop indexes add up to the target sum.
  4. If nums[outerLoopIndex] + nums[innerLoopIndex] is equal to target, return {outerLoopIndex, innerLoopIndex} as result. Else continue iteration to check for the next pair.
  5. Repeat the above steps until you find a combination that adds up to the given target.

For example, for array [7,2,13,11] and target sum 24, we fix the outer loop at index i=0 i.
e element 7 and check it with all possible values of the inner loop from j=i+1 to j=n-1, i.e from index 1 to 3.
So, we will be checking the following pair of elements in the first iteration of outer loop: (7,2) (7,13) and (7,11).
Now we increment the outer loop index i by 1 and check it with indices 2 to 3 (i+1 to n-1) of the inner loop.
We repeat this until we find the required answer.

Note: n here is the size of the array.

Code

Language: Go

func TwoSum(nums []int, target int) []int {
	n := len(nums)
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if nums[i]+nums[j] == target {
				return []int{i, j}
			}
		}
	}
	return []int{}
}

In the worst case, this algorithm has a running time complexity of O(n^2).
The worst case would occur when the required combination is the last combination to be checked by our loops.

Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(1)

你可能感兴趣的:(leetcode,leetcode,golang,算法)