class Solution {
public int numIdenticalPairs(int[] nums) {
int goodPairs = 0;
int[] counts = new int[101];
for (int num: nums) {
goodPairs = counts[num];
counts[num] ;
}
return goodPairs;
}
}
This is one of the solution for Number of good pairs problem which is in leetcode. can anyone explain this for loop block.
CodePudding user response:
The int[] nums
contains source
data.
So let's imagine the following.
We have the following data
int nums[] = { 1, 2, 1 };
At the beginning we defined the variable goodPairs
to the 0
and we initialized the new array int[] counts
. Every 101
positions of this array has the 0
value. So it might looks like:
int counts[] = { 0, 0, 0, 0, 0, 0, ......... n} //n is the 101-th position
In for loop we are looping over the nums array
and doing this:
goodPairs = goodPairs counts[1]; //at the first time goodPairs = 0, counts[1] is 0
counts[1] = counts[1] 1; //then we increment the value at the `num` position (in this case is the `num` 1 - the first value from our array `nums[]`)
The result of goodPairs is after first loop 0
, and the count at the first position is 1
int counts[] = { 0, 1, 0, 0, 0, 0, ......... n} //n is the 101-th position
Second looping:
goodPairs = goodPairs counts[1]; //at the second time goodPairs = 0, counts[2] is 0
counts[2] = counts[2] 1; //then we increment the value at the `num` position (in this case is the `num` 2 - the third value from our array `nums[]`)
The result of goodPairs is after second loop still 0
, and the count at the first position is 1
and at the second too
int counts[] = { 0, 1, 1, 0, 0, 0, ......... n} //n is the 101-th position
The last looping:
goodPairs = goodPairs counts[1]; //at the second time goodPairs = 0, counts[1] is now 1
counts[1] = counts[1] 1; //then we increment the value at the `num` position (in this case is the `num` 1 - the second value from our array `nums[]`)
So the result will be
goodPairs = 1;
int counts[] = { 0 (quantity of number 0), 2 (quantity of number 1), 1 (quantity of number 2), 0 (quantity of number 3), 0 (quantity of number 3), 0 (quantity of number 4), ......... n} //n is the 101-th position
Now you know that there are two numbers 1
and one number 2
in your array nums[]
- from counts[]
array
CodePudding user response:
In this code you used for each loop which is also same as for loop but without condition. The For each loop just traversal here with holding the variable "num" which the values from "nums".Nums is the array which is going to traveral for every time loop runs the goodpairs variable is -1 of the array(count).Especially count[num] increases the value not index
for eg: if the count is 2 then the goodpair is 1.
By using this logic the good pairs of array is found and the formula is (n*(n-1))/2
At the end, The count array Index>=1 is filled with 1