Golang Leetcode 321. Create Maximum Number.go

Keywords: github

thinking

This is a Hard topic. The whole problem can be divided into several steps:
1) Extract the largest array containing i elements from an array of length N;
2) Combine two arrays of length M and N and make the largest array.
3) i traverses from 0 to K to find the optimal solution. [The specific minimum of i is the maximum between 0 and K-nums2.size(), and the maximum of i is calculated in the same way]

code

func maxNumber(nums1 []int, nums2 []int, k int) []int {
	ans := []int{}
	if len(nums1) == 0 && len(nums2) == 0 {
		return ans
	}
	if len(nums1) == 0 {
		return nums2[:k]
	}
	if len(nums2) == 0 {
		return nums1[:k]
	}
	for i := 0; i < k; i++ {
		if i > len(nums1) || k-i > len(nums2) {
			continue
		}
		m := mergeArray(maxArray(nums1, i), maxArray(nums2, k-i))
		if arrayToStr(ans) < arrayToStr(m) {
			ans = m
		}
	}
	return ans
}

//Arrays are converted into strings to compare sizes
func arrayToStr(nums []int) string {
	ret := ""
	str := []string{}
	if len(nums) == 0 {
		return ret
	}
	for _, v := range nums {
		str = append(str, strconv.Itoa(v))
	}
	return strings.Join(str, "")
}

//Merge two arrays to get the largest array without changing the order
func mergeArray(nums1, nums2 []int) []int {
	if len(nums1) == 0 {
		return nums2
	}
	if len(nums2) == 0 {
		return nums1
	}
	ans := []int{}
	i, j := 0, 0
	for i < len(nums1) && j < len(nums2) {
		if bigArray(nums1[i:], nums2[j:]) {
			ans = append(ans, nums1[i])
			i++
		} else {
			ans = append(ans, nums2[j])
			j++
		}
	}
	if i < len(nums1) {
		ans = append(ans, nums1[i:]...)
	}
	if j < len(nums2) {
		ans = append(ans, nums2[j:]...)
	}
	return ans
}

//Take the largest value of the first k in the array
func maxArray(nums []int, k int) []int {
	ans := []int{}
	if k == 0 {
		return ans
	}
	l := len(nums)
	toPop := 0
	if l <= k {
		return nums
	} else {
		toPop = l - k
	}

	for _, v := range nums {
		for len(ans) > 0 && v > ans[len(ans)-1] && toPop > 0 {
			ans = ans[:len(ans)-1]
			toPop--
		}
		ans = append(ans, v)
	}
	return ans[:k]
}

//Compare the size of two arrays, and return true if the former is larger than the latter

func bigArray(nums1, nums2 []int) bool {
	l1, l2 := len(nums1), len(nums2)
	l := 0
	if l1 > l2 {
		l = l2
	} else {
		l = l1
	}
	for i := 0; i < l; i++ {
		if nums1[i] == nums2[i] {
			continue
		}
		if nums1[i] > nums2[i] {
			return true
		} else {
			return false
		}
	}
	if l1 > l2 {
		return true
	}
	return false
}

For more information, please go to my repo: https://github.com/anakin/golang-leetcode

Posted by angulion on Sun, 07 Apr 2019 20:06:29 -0700