1. Two Sum - LeetCode

2017.07.25 21:52* 字数 302

1. Two Sum - LeetCode


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.


Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Approach #1 (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.

Version 1

func twoSum(nums []int, target int) []int {
    indexs := make([]int, 2)
    for i := 0; i < len(nums); i++ {
        for j := i + 1; j < len(nums); j++ {
            if target - nums[i] == nums[j] {
                indexs[0] = i
                indexs[1] = j
    return indexs

Submission Details

Version 2

func twoSum(nums []int, target int) [] int {
    answer := make([]int, 2)
    for i, _ := range nums {
    //for i := range nums {
        for j := i + 1; j < len(nums); j++ {
            if nums[i]+nums[j] == target {
                answer[0] = i
                answer[1] = j
    return answer

Submission Details

Some Explainations


Effective Go
Package builtin
Making slices, maps and channels

The blank identifier

Effective Go

For Loop

For statements

Range clause

Go by Example: Range

NOTE: A same code runs at the second time, the runtime may be different. This may be due to a lot of different things but a common reason is that the execution server uses dynamic frequency management on the CPU. This means the server's CPU runs at a lower frequency when the server gets too hot in order to avoid overheating and risk of component damage.

Therefore, it is normal that when the server is under light load because very few people are submitting jobs, you run at maximum speed.

Another reason may be OS preemption, meaning the operative system takes control of the CPU (to handle some interrupt, for example), interrupting your program.

A common way to work under this situations is to measure performance in terms of number of CPU cycles required to run the program. There are profiling tools that do exactly that. This way, it doesn't matter if the CPU frequency varies or the OS pushes your program out for a few milliseconds.