Created
March 27, 2020 20:45
-
-
Save alldroll/65ce32d831d5cfc89c664ba919bcb591 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://leetcode.com/problems/intersection-of-two-arrays-ii | |
| import "sort" | |
| func intersect(nums1 []int, nums2 []int) []int { | |
| sort.Ints(nums1) | |
| sort.Ints(nums2) | |
| if len(nums1) > len(nums2) { | |
| nums1, nums2 = nums2, nums1 | |
| } | |
| result := []int{} | |
| for len(nums1) > 0 && len(nums2) > 0 { | |
| target := nums1[0] | |
| nums1 = nums1[1:] | |
| j := sort.Search(len(nums2), func (i int) bool { | |
| return nums2[i] >= target | |
| }) | |
| if j == len(nums2) { | |
| break | |
| } | |
| if nums2[j] == target { | |
| result = append(result, target) | |
| nums2 = nums2[j + 1:] | |
| } else { | |
| nums2 = nums2[j:] | |
| } | |
| if len(nums1) > len(nums2) { | |
| nums1, nums2 = nums2, nums1 | |
| } | |
| } | |
| return result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment