Please implement a function that takes an array of integers and a target value as input, and finds two numbers in the array such that their sum is equal to the target value.

Today’s AI written test questions:

AI Golang written test intermediate questions icon-default.png?t=N7T8https://bs.rongapi.cn/1702565828114780160/23

Complete title:

Please implement a function that takes an array of integers and a target value as input, and finds two numbers in the array such that their sum is equal to the target value. The function should return the indices of these two numbers, where index 1 must be less than index 2. It can be assumed that each input corresponds to only one answer, and the same elements are not reused. For example, given the array [2, 7, 11, 15] and the target value 9, since nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

Idea:

After getting this question, my first instinct is to directly double loop, loop to get the first number, search for the second number among the remaining ones, and submit it if found.

As an intermediate question, we still need to do some optimization.

My optimization idea is that since I have made a loop, is it possible to cache some data in the process to speed up subsequent searches?

At first I was wondering whether to do a sorting directly, but then I felt that sorting itself also requires calculations, and this question does not require complete sorting, so it should be faster than sorting.

Following this idea, I think since I compare a value each time, I can divide the original data into two parts according to size during this process?

In this way, once the outer layer is looped, I can get a group with a finer granularity. For next comparison, values ​​that are too small and too large can be ignored directly, and then the hit array is divided into two, such as the above example. , if I search for 2 for the second time, then I only need to compare the first group below 5, and skip the second group directly.

The submission result is in the initial link, but after submission, AI feels that the problem is as follows:

Answer evaluation: The code logic is basically correct, but there are some redundant parts. The processing of grouping can be simplified, and map can be used to store elements that have been traversed to improve search efficiency.

I just remembered that I could just use map... It's an edge loop, which stores the position and value information in a map. If there is a corresponding value in the map, it will be taken out and returned directly. If not, it will be looped again.

However, my solution is still helpful for situations where multiple possible values ​​need to be returned. I will post the revised solution for everyone to correct me:


type Group struct {
	Seperator *int
	Values    [][2]int
}

func seperateGroup(seperator int, group *Group) (loc int, smallerGroup *Group, biggerGroup *Group, matched bool) {
	smallerGroup, biggerGroup = &Group{
		Seperator: &seperator,
	}, &Group{
		Seperator: group.Seperator,
	}
	for j := 0; j < len(group.Values); j++ {
		if group.Values[j][0] == seperator {
			return j, nil, nil, true
		} else if group.Values[j][0] < seperator {
			smallerGroup.Values = append(smallerGroup.Values, group.Values[j])
		} else {
			biggerGroup.Values = append(biggerGroup.Values, group.Values[j])
		}
	}
	return 0, smallerGroup, biggerGroup, false
}

func recurse(loc int, arr []int, target int, groups ...*Group) []int {
	if loc == len(arr)-1 {
		return nil
	}
	var cur = arr[loc]
	var remain = target - cur
	var newGroups []*Group
	i := 0
	for ; i < len(groups); i++ {
		if groups[i].Seperator == nil || remain <= *groups[i].Seperator {
			remainLoc, smallerGroup, biggerGroup, matched := seperateGroup(remain, groups[i])
			if matched {
				return []int{loc, groups[i].Values[remainLoc][1]}
			}
			if i == 0 {
				newGroups = []*Group{smallerGroup, biggerGroup}
			} else {
				newGroups = append(groups[:i-1], smallerGroup, biggerGroup)
			}
			break
		}
	}
	if i < len(groups)-1 {
		newGroups = append(newGroups, groups[i+1:]...)
	}
	return recurse(loc+1, arr, target, newGroups...)
}

// 主函数入口
func FindMatchGroup(arr []int, target int) []int {

	if len(arr) < 2 {
		return nil
	}

	var remain = &Group{}
	for i := 1; i < len(arr); i++ {
		remain.Values = append(remain.Values, [2]int{arr[i], i})
	}

	return recurse(0, arr, target, remain)
}

Guess you like

Origin blog.csdn.net/baijiafan/article/details/133174054