Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2364. Count Number of Bad Pairs #133

Open
Woodyiiiiiii opened this issue Aug 10, 2022 · 0 comments
Open

Leetcode 2364. Count Number of Bad Pairs #133

Woodyiiiiiii opened this issue Aug 10, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Method: hash
Key points:

  1. convert varying condition to constant condition, that is to convert "j - i != nums[j] - nums[i]" to "j - nums[j] != i - nums[i]"
  2. use reverse method, that is to "i - prev"
class Solution {
    public long countBadPairs(int[] nums) {
        long ans = 0;
        int n = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        
        // convert "j - i != nums[j] - nums[i]" to "j - nums[j] != i - nums[i]"
        for (int i = 0; i < n; ++i) {
            int prev = map.getOrDefault(i - nums[i], 0);
            // prev represents the number of equal, so need "i - prev"
            ans += (i - prev);
            map.put(i - nums[i], prev + 1);
        }
        
        return ans;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant