349. Intersection of Two Arrays--LeetCode Record

Tong_hdj發表於2016-07-10

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))
    }
    }

相關文章