commit b2a0edc84d24edc9f0e722dbb8d926a14d1efdc4 parent 1c99e5756e5dbda6374f3746deb22d8b83c38e29 Author: AndrewLockVI <andrewlaack1@gmail.com> Date: Mon, 5 Jun 2023 12:18:56 -0500 Completed number of good pairs using dart Diffstat:
| A | number-of-good-pairs/number-of-good-pairs.dart | | | 40 | ++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 40 insertions(+), 0 deletions(-)
diff --git a/number-of-good-pairs/number-of-good-pairs.dart b/number-of-good-pairs/number-of-good-pairs.dart @@ -0,0 +1,40 @@ +//Given a list of numbers return the number of good pairs +//that can be returned. A good pair is there n[i] == n[j] and +//i < j. + +//To solve this I created a hashmap with all of the values and +//the index they occured at. Then from there I iterated through +//the map and added the total number of pairs that could be created +//from each number. + +//The time complexity of this is O(n). + +//Time: 219ms Beats: 100% +//Memory: 144.2MB Beats: 8.57% + +class Solution { + int numIdenticalPairs(List<int> nums) { + Map<int,List<int>> vals = {}; + int count = 0; + for(int i in nums){ + List<int> current = (vals[i] ?? []); + current.add(count); + vals[i] = current; + count += 1; + } + int options = 0; + for(var entry in vals.entries){ + List<int> curr_list = entry.value; + options += sumAll(curr_list.length - 1); + } + return options; + } + int sumAll(int original){ + if(original <= 1){ + return original; + } + int current = sumAll(original - 1); + current = current + original; + return current; + } +}