349. Intersection of Two Arrays--LeetCode Record
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))
}
}
相關文章
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- leetcode 350. Intersection of Two Arrays IILeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- 懶載入之intersection observerServer
- CF1093E [Intersection of Permutations]
- halcon學習擴充系列—交集intersection的擴充運算元intersection_expand
- screen-record
- Active Record Associations
- react-recordReact
- coca after two months vs in two months
- Java泛型裡的Intersection TypeJava泛型
- leetcode 349. 兩個陣列的交集LeetCode陣列
- 349.兩個陣列的交集|python陣列Python
- Camera List Record - 120
- Daily record-SeptemberAI
- Learn and Record12
- ES6+ ---- record
- 精讀《react-intersection-observer 原始碼》ReactServer原始碼
- 力扣-349. 兩個陣列的交集力扣陣列
- 實戰 Java 16 值型別 Record - 2. Record 的基本用法Java型別
- Homework record-Simple sorting
- Travel Notes-Record mood
- Two Pirates - 2
- Two Pointer Method
- Java 21 新特性:Record PatternsJava
- gorm忽略報錯: record not foundGoORM
- Java 16 新特性:record類Java
- Erlang中的Record詳解
- Record It for Mac錄屏軟體Mac
- 淺析 record 使用場景
- BULK In-BIND與RECORD(轉)
- Renovation Tour-Record my home
- Simple, Fast Malicious Multiparty Private Set Intersection-解讀AST
- Scalable Multi-Party Private Set-Intersection-解讀
- Intersection observer檢測元素是否在視窗內Server
- 使用Intersection Observer API建立無限載入元件ServerAPI元件
- 11.23 Two Different Worlds
- LeetCode | 1 Two SumLeetCode
- Tokitsukaze and Two Colorful Tapes