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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/69719.html
摘要:由于無法處理相同的操作,所依對于的時候,我采用了進行操作。為時,對于每一次遍歷,找到這個值是否已經存在在里,同時獲取這個值出現過的次數。 題目詳情 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...
摘要:前言從開始寫相關的博客到現在也蠻多篇了。而且當時也沒有按順序寫現在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關的博客到現在也蠻多篇了。而且當時也沒有按順序寫~現在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個索引嘻嘻。 順序整理 1~50 1...
摘要:暴力解法就是時靈時不靈,兩次一次。希望看到的大神能夠分享優質的解法謝謝大家 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...
閱讀 1536·2023-04-26 02:08
閱讀 3128·2021-10-14 09:42
閱讀 7177·2021-09-22 15:34
閱讀 3236·2019-08-30 13:16
閱讀 2719·2019-08-26 13:49
閱讀 1342·2019-08-26 11:59
閱讀 1251·2019-08-26 10:31
閱讀 2170·2019-08-23 17:19