How can I efficiently determine if one slice of integers is a subset of another in Go using a map?

Barbara Streisand
Release: 2024-10-27 08:11:31
Original
838 people have browsed it

How can I efficiently determine if one slice of integers is a subset of another in Go using a map?

Subset Check with Integer Slices in Go using Map

Determining if one slice of integers is a subset of another requires an efficient solution beyond simple iteration. This article introduces a solution that utilizes a map to optimize the check.

Subset Definition

A slice is considered a subset of another if it contains all the elements of the latter, with the possible inclusion of duplicates. For instance, {1, 2, 3} is a subset of {1, 2, 3, 4}, while {1, 2, 2} is not a subset of {1, 2, 3, 4}.

Map-Based Implementation

The provided solution employs a map to efficiently determine if a slice is a subset. It constructs a map from the second slice, with each element's count as the value. Subsequently, it iterates through the first slice and verifies the presence of each element in the map. If all elements are found with sufficient duplicates, the first slice is deemed a subset.

Sample Code

<code class="go">import "fmt"

// subset returns true if the first array is completely
// contained in the second array. There must be at least
// the same number of duplicate values in second as there
// are in first.
func subset(first, second []int) bool {
    set := make(map[int]int)
    for _, value := range second {
        set[value]++
    }

    for _, value := range first {
        if count, ok := set[value]; !ok {
            return false
        } else if count < 1 {
            return false
        } else {
            set[value] = count - 1
        }
    }

    return true
}

func main() {
    fmt.Println(subset([]int{1, 2, 3}, []int{1, 2, 3, 4}))
    fmt.Println(subset([]int{1, 2, 2}, []int{1, 2, 3, 4}))
}</code>
Copy after login

Output

true
false
Copy after login

Conclusion

This map-based solution efficiently determines whether one integer slice is a subset of another, handling potential duplicate values. It provides an optimized approach to solving this common problem in Go.

The above is the detailed content of How can I efficiently determine if one slice of integers is a subset of another in Go using a map?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!