[Swift]LeetCode532. 数组中的K-diff数对 | K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Note:

  1. The pairs (i, j) and (j, i) count as the same pair.
  2. The length of the array won‘t exceed 10,000.
  3. All the integers in the given input belong to the range: [-1e7, 1e7].

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         var count:Int = 0
 4         if k < 0 {return count}
 5         var hm:[Int:Int] = [Int:Int]()
 6         let len:Int = nums.count
 7         for i in 0..<len
 8         {
 9             hm[nums[i]] = i
10         }
11         for i in 0..<len
12         {
13 //如果字典包含所请求键的值,则下标返回包含该键的现有值的可选值。否则,下标返回nil:
14             if let keys = hm[nums[i] + k]
15             {
16                 if keys != i
17                 {
18                     count += 1
19 //使用下标语法通过nil为该键指定值来从字典中删除键值对
20 //使用该removeValue(forKey:)方法从字典中删除键值对。hm.removeValue(forKey:key)
21 //此方法删除键值对(如果存在)并返回已删除的值,nil如果不存在值则返回
22                     hm[nums[i] + k] = nil
23                 }
24             }
25         }
26         return count
27     }
28 }


44ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         guard k >= 0 else {
 4             return 0
 5         }
 6
 7         var dict = [Int: Int]()
 8         for num in nums {
 9             //dict[num] = dict[num] == nil ? 0 : dict[num]! + 1
10             dict[num, default: 0] += 1
11         }
12
13         var res = 0
14         for (num, count) in dict {
15             if k == 0 {
16                 if count > 1 {
17                     res += 1
18                 }
19             } else {
20                 if dict[num - k] != nil {
21                     res += 1
22                 }
23             }
24
25         }
26         return res
27     }
28 }


48ma

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         guard nums.count > 1 else { return 0 }
 4         guard k >= 0 else { return 0 }
 5
 6         var res = 0
 7         var dict = [Int: Int]()
 8         for n in nums {
 9             if let val = dict[n] {
10                 dict[n] = val + 1
11             } else {
12                 dict[n] = 1
13             }
14         }
15
16         if k == 0 {
17             return dict.reduce(0) { (r, arg1) -> Int in
18                 if arg1.value > 1 {  return r + 1}
19                 return r
20             }
21         } else {
22             for key in dict.keys {
23                 if dict.keys.contains(key + k) {
24                     res = res + 1
25                 }
26             }
27             return res
28         }
29     }
30 }


52ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         guard k >= 0 else {
 4             return 0
 5         }
 6
 7         var dict = [Int: Int]()
 8         for num in nums {
 9             dict[num, default: 0] += 1
10         }
11
12         var res = 0
13         for (num, count) in dict {
14             if k == 0 {
15                 if count > 1 {
16                     res += 1
17                 }
18             } else {
19                 if dict[num - k] != nil {
20                     res += 1
21                 }
22             }
23
24         }
25         return res
26     }
27 }


56ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         var dict = [Int: Bool]()
 4
 5         if k < 0 {
 6             return 0
 7         }
 8
 9         var diff = k < 0 ? -1*k : k
10         var count = 0
11
12
13
14         for num in nums {
15             if !dict.keys.contains(num) {
16                 dict[num] = false
17                 if diff == 0 { continue }
18             }
19
20             if dict.keys.contains(num-diff) {
21                 if dict[num-diff] == false {
22                     dict[num-diff] = true
23                     count = count + 1
24                 }
25
26             }
27             if dict.keys.contains(num+diff) {
28                 if dict[num] == false {
29                     dict[num] = true
30                     count = count + 1
31                 }
32             }
33         }
34
35         return count
36     }
37 }


68ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3
 4         guard k >= 0 else { return 0 }
 5
 6         var dict = nums.reduce(into: [Int: Int]()) { dict, num in
 7             dict[num, default:0] += 1
 8         }
 9
10         guard k > 0 else {
11             return dict.reduce(into: 0) { count, numAndCount in
12                 if numAndCount.1 > 1 {
13                     count += 1
14                 }
15             }
16         }
17
18         var totalCount = 0
19         for (num, count) in dict {
20             if dict[num+k, default:0] > 0 {
21                 totalCount += 1
22             }
23             if dict[num-k, default: 0] > 0 {
24                 totalCount += 1
25             }
26             dict[num] = 0
27         }
28
29         return totalCount
30     }
31 }


76ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3
 4         guard k >= 0 else { return 0 }
 5
 6         var dict = nums.reduce(into: [Int: Int]()) { dict, num in
 7             dict[num, default:0] += 1
 8         }
 9
10         if k == 0 {
11             return dict.values.reduce(into: 0) { total, appearances in
12                 if appearances > 1 {
13                     total += 1
14                 }
15             }
16         }
17
18         return dict.keys.reduce(into: 0) { total, num in
19             if dict[num+k, default:0] > 0 {
20                 total += 1
21             }
22             if dict[num-k, default: 0] > 0 {
23                 total += 1
24             }
25             dict[num] = 0
26         }
27
28     }
29 }


96ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         guard nums.count > 1 else { return 0}
 4         let sortedNums = nums.sorted()
 5         var behind = 0
 6         var forward = 1
 7         var counter = 0
 8
 9         while forward < nums.count , behind < nums.count {
10             if behind >= forward {
11                 forward = behind + 1
12                 continue
13             }
14
15             let diff = abs(sortedNums[forward] - sortedNums[behind])
16
17             if diff < k {
18                 repeat { forward += 1} while forward < nums.count && sortedNums[forward] == sortedNums[forward-1]
19                 continue
20             }
21
22             if diff == k {
23                 counter += 1
24                 repeat { forward += 1} while forward < nums.count && sortedNums[forward] == sortedNums[forward-1]
25                 repeat { behind += 1} while behind < nums.count && sortedNums[behind] == sortedNums[behind-1]
26                 continue
27             }
28
29             if diff > k {
30                 repeat { behind += 1} while behind < nums.count && sortedNums[behind] == sortedNums[behind-1]
31                 continue
32             }
33         }
34         return counter
35     }
36 }


116ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         let nums =  nums.sorted()
 4         var i = 0
 5         var j = 1
 6         var res = 0
 7         while  i < nums.count && j < nums.count  {
 8             if nums[j] - nums[i] == k {
 9                 res += 1
10                 i += 1
11                 j += 1
12                 while j < nums.count && nums[j] == nums[j-1]  {
13                     j += 1
14                 }
15             }else if nums[j] - nums[i] < k {
16                 j += 1
17             }else  {
18                 i += 1
19                 j = i < j ? j : i+1
20             }
21         }
22         return res
23     }
24 }


132ms

 1 class Solution {
 2     func findPairs(_ nums: [Int], _ k: Int) -> Int {
 3         guard nums.count > 1 else {
 4             return 0
 5         }
 6         var resultSet: [[Int]] = []
 7         var sortedNums = nums
 8         sortedNums.sort()
 9         var firstPointer = 0
10         var secondPointer = 1
11         while secondPointer < sortedNums.count {
12             // print("comparing : \(sortedNums[firstPointer]) and \(sortedNums[secondPointer])")
13             if abs(sortedNums[firstPointer] - sortedNums[secondPointer]) == k {
14                 var validList: [Int] = [sortedNums[firstPointer], sortedNums[secondPointer]]
15                 // if !resultSet.contains(where: {$0 == validList}) {
16                     resultSet.append(validList)
17                 // }
18                 firstPointer += 1
19             } else if (sortedNums[secondPointer] - sortedNums[firstPointer]) < k {
20                 secondPointer += 1
21             } else {
22                 firstPointer += 1
23             }
24             if firstPointer == secondPointer {
25                 secondPointer += 1
26             }
27         }
28         print("This is the result set : \(resultSet)")
29         var removeIndex:[Int] = []
30         if resultSet.count > 1 {
31             for index in 1..<resultSet.count {
32                 // print("index : \(index)")
33                 if resultSet[index] == resultSet[index-1] {
34                     removeIndex.append(index)
35                 }
36             }
37         }
38         while removeIndex.count != 0 {
39             // print("removing \(removeIndex.last) as \(removeIndex)")
40             resultSet.remove(at: removeIndex.last!)
41             let _ = removeIndex.popLast()
42         }
43         return resultSet.count
44     }
45 }

原文地址:https://www.cnblogs.com/strengthen/p/9813030.html

时间: 2024-08-03 06:48:35

[Swift]LeetCode532. 数组中的K-diff数对 | K-diff Pairs in an Array的相关文章

找到数组中唯一重复的数

#include<iostream> #include<algorithm> #include<numeric> using namespace std; int helper1(int a[],int n) { int sum = accumulate(a,a+n,0); int sum2 = n*(n-1)/2; return sum-sum2; } int helper2(int a[],int n) { int bitor = a[0]^0; for(int i

(算法)求数组中出现频率最高的数

不准备实现算法先,根据21题和前辈的经验,这道题的真正考核点不在于解决这个问题,而在于拿到这个问题以后题的问题. 正常的一个做法,一次扫描然后用HASHMAP进行一个统计,然后再扫描一次HASHMAP获得频率最高的数.时间是O(N)空间也是O(N). 还有一种是做排序,然后扫描一次根据下标计算可以得到频率最高的数(可以避免空间消耗?). (不知道是否还有别的做法?) 据说我们应该先问这个数组是否已经排序?(想得美) 然后是否已经知道这个数的大概出现频率(比如说超过一半) 是否可以用额外空间?是否

3.键盘输入10个数,放到数组中,(1)去除该数组中大于10的数 (2)将该数组中的数字写入到本地文件number.txt中

package cn.it.text; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /* * 3.键盘输入10个数,放到数组中 (1)去除该数组中大于10的数 (2)将该数组中的数字写入到本地文件number.txt中 */ public class Test3 { public static int[] arr = new int[10]; public static void

数组中出现最多的数,以及接口 Map.Entry&lt;K,V&gt;

1 package test.tools; 2 3 import java.util.Collection; 4 import java.util.Collections; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 public class TestArr { 9 10 public static void MaxCount(int[] arr) { 11 Map<Integer, Integer> map = new Ha

[算法]在数组中找到出现次数大于N/K的数

题目: 1.给定一个整型数组,打印其中出现次数大于一半的数.如果没有出现这样的数,打印提示信息. 如:1,2,1输出1.    1,2,3输出no such number. 2.给定一个整型数组,再给一个整数K,打印所有出现次数大于N/K的数,如果没有这样的数,打印提示信息. 解答: 两道题都可以使用哈希表记录每个数出现的次数,额外的空间复杂度为O(N). 其他的方法: 1.时间复杂度为O(N).额外空间复杂度为O(1). public static void printHalfMajor(in

找出数组中唯一重复的数(转)

题目: 数组a[N],1至N-1这N-1个数存放在a[N]中,其中某个数重复一次.写一个函数,找出被重复的数字. 方法一:异或法. 数组a[N]中的N个数异或结果与1至N-1异或的结果再做异或,得到的值即为所求. 设重复数为A,其余N-2个数异或结果为B. N个数异或结果为A^A^B 1至N-1异或结果为A^B 由于异或满足交换律和结合律,且X^X = 0  0^X = X; 则有 (A^B)^(A^A^B)=A^B^B=A 代码: #include <stdio.h> #include &l

找出有序数组中绝对值最小的数

问题: 一个有序数组,值有可能有负值,也有可能没有,现需要找出其中绝对值最小的值. 方法1: 遍历数组,找到绝对值最小值,时间复杂度O(n),n为元素个数. 方法2: 二分查找,因为数组有序,可以利用二分查找,时间复杂度O(logn). 分析步骤: 如果第一个数为正数,说明整个数组没有负数,直接返回第一个数 如果最后一个数为负数,说明整个数组没有正数,直接返回最后一个数 数组元素有正有负,说明绝对值最小的元素肯定在正负数交界处,需要二分查找上场: 如果a[mid]<0,因为数组是升序,说明绝对值

有序二维数组中搜索特定的数

关于二维有序数组中搜索,其题目如下: 给定一个矩阵,都是整数,每一行从左到右升序,每一列从上到下有序,例如下面的矩阵 [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] 请用最快的时间找出特定的数,例如,输入3,存在这个数,输入15,不存在这个数. 实现如下的函数bool FindArray(int *pArray,int nWidth,int nheight,int nKey). 最笨的方法是逐个遍历进行比较,如果是这样,这题目就没什么意义

如何找出数组中第二大的数

1.最容易想到的办法 我们可以用最简单的办法来找到一个数组中任意大小的数字,那就是按照某一个排序方式将数组的所有元素进行排序,然后按需取出来就可以,知识这种方式的时间复杂度和空间复杂度比较大,所以,有了下面这种方式 2.通过设置两个变量来进行判断 这种方式可以只通过一遍扫描数组即可找到第二大数,具体的形式如下:先定义两个变量:一个变量用来存储数组的最大数,初始值为数组首元素,另一个变量用来存储第二大的数,初始值为最小负整数,然后遍历数组元素,如果数组元素的值比最大数变量还大,更新最大数:若数组元