SUM

tangr206

https://leetcode.com/problems...

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

  • Learn how to use sort in golang

  • Solution1: search

In a sorted array, find a[i] + a[j] == target

when a[beg] + a[end] > target, we have two options:

  1. beg-- we have already tried a[beg-1] + a[end], which not equal to target, can ignore

  2. end-- go ahead

when a[beg] + a[end] < target

  1. beg++ go ahead

  2. end++ tried before

  • Solution2: Using Map

import "sort"

type Node struct {
    Value int
    Index int
}

type ByVal []*Node
func (byVal ByVal) Len() int {return len(byVal)}
func (byVal ByVal) Swap(i, j int)  { byVal[i], byVal[j] = byVal[j], byVal[i] }
func (byVal ByVal) Less(i, j int) bool { return byVal[i].Value < byVal[j].Value }


func twoSum(nums []int, target int) []int {
    
    nodeList := make([]*Node, 0)
    for index, num := range nums {
        nodeList = append(nodeList, &Node{Value:num, Index:index})
    }
    
    sort.Sort(ByVal(nodeList))
    //fmt.Printf("%v\n", nodeList)
    
    res := make([]int, 0)
    beg := 0; 
    end := len(nodeList) - 1;
    for beg < end {
        cur := nodeList[beg].Value + nodeList[end].Value
        if cur == target {
            res = append(res, nodeList[beg].Index)
            res = append(res, nodeList[end].Index)
            break
        }
        if cur > target {
            end--
        } 
        if cur < target {
            beg++
        } 
    }
    sort.Ints(res)
    return res
}
阅读 1.2k

tangr206
My Blog
1 声望
0 粉丝
0 条评论
1 声望
0 粉丝
文章目录
宣传栏