349. Intersection of Two Arrays--LeetCode Record

本文介绍了一种计算两个整数数组交集的算法实现。通过示例说明如何找到两个数组中的公共元素,并确保结果中每个元素都是唯一的。提供了两种不同的Swift实现方案:一种是手动实现的迭代方法,另一种是利用集合的交集操作简化处理。

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:
Each element in the result must be unique.
The result can be in any order.

基础不过关,被略惨了!

自己的代码

class Solution {
    func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] {

        if nums1.count == 0 || nums2.count == 0 {
            return []
        }

        // 取大数组放置在numsUse1
        var numsUse1:[Int] = []
        var numsUse2:[Int] = []
        if nums1.count > nums2.count {
            numsUse1 = nums1
            numsUse2 = nums2
        }else {
            numsUse1 = nums2
            numsUse2 = nums1
        }
        removeSimilar(&numsUse1)
        removeSimilar(&numsUse2)

        var nums1Count = numsUse1.count
        var numsIndex:[Int] = []

        // 增长numsUse1
        for index in 0..<numsUse2.count-1 {
            numsUse1.append(numsUse1[index])
        }

        // 移动对比numsUse1和numsUse2
        for index1 in 0..<nums1Count {
            for index2 in 0..<numsUse2.count{
                if numsUse1[index1 + index2] == numsUse2[index2] {
                    //  存取下表
                    let insertIndex = (index1 + index2) % nums1Count
                    numsIndex.append(insertIndex)
                }
            }
        }

        // 过滤结果,以长的为例,按长的顺序输出
        numsIndex = numsIndex.sort({$0 < $1})
        var numsFinally:[Int] = []
        var index:Int = 0
        while index < numsIndex.count {
            numsFinally.append(numsUse1[numsIndex[index]])
            index++
        }

        return numsFinally
    }

    func removeSimilar(inout nums: [Int]) {
        var index:Int = 0
        var nextIndex:Int = 0
        while index < nums.count {
            nextIndex = index + 1
            while nextIndex < nums.count {
                if nums[index] == nums[nextIndex] {
                    nums.removeAtIndex(nextIndex)
                }else {
                    nextIndex++
                }
            }
            index++
        }
    }

}

别人的代码

class Solution {
    func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] {
        return [Int](Set<Int>(nums1).intersect(nums2))
    }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值