Problem
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.
ExampleExample 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).
public class Solution { /** * @param nums: an array of integers * @param k: an integer * @return: the number of unique k-diff pairs */ public int findPairs(int[] nums, int k) { //it actually wants unique pairs, so need to sort and leave out the duplicates Arrays.sort(nums); int count = 0; for (int i = 0; i < nums.length-1; i++) { if (i != 0 && nums[i] == nums[i-1]) continue; for (int j = i+1; j < nums.length; j++) { if (j != i+1 && nums[j] == nums[j-1]) continue; if (nums[j] - nums[i] == k) count++; } } return count; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/69719.html
摘要:由于無法處理相同的操作,所依對于的時(shí)候,我采用了進(jìn)行操作。為時(shí),對于每一次遍歷,找到這個(gè)值是否已經(jīng)存在在里,同時(shí)獲取這個(gè)值出現(xiàn)過的次數(shù)。 題目詳情 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-d...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個(gè)索引嘻嘻。 順序整理 1~50 1...
摘要:暴力解法就是時(shí)靈時(shí)不靈,兩次一次。希望看到的大神能夠分享優(yōu)質(zhì)的解法謝謝大家 Problem For an array A, if i < j, and A[i] > A[j], called (A[i], A[j]) is a reverse pair.return total of reverse pairs in A. Example Given A = [2, 4, 1, 3, ...
Problem Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, great acting skills a...
LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...
閱讀 1550·2023-04-26 02:08
閱讀 3139·2021-10-14 09:42
閱讀 7230·2021-09-22 15:34
閱讀 3250·2019-08-30 13:16
閱讀 2751·2019-08-26 13:49
閱讀 1355·2019-08-26 11:59
閱讀 1286·2019-08-26 10:31
閱讀 2178·2019-08-23 17:19