SUM

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

Given an array of integers, return indices of the two numbers such that they add up to a specific target.golang

You may assume that each input would have exactly one solution, and you may not use the same element twice.app

Example:
Given nums = [2, 7, 11, 15], target = 9,code

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].ip

  • Learn how to use sort in golangci

  • Solution1: searchelement

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

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

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

  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
}
相關文章
相關標籤/搜索