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题解:220. 存在重复元素 III,暴力法,JavaScript,详细注释 #365

Open
chencl1986 opened this issue Aug 16, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:220. 存在重复元素 III

解题思路:

  1. 使用双循环遍历所有可能的下标ij,并根据要求判断下标是否满足条件,满足则返回true
  2. 如果能退出循环,表示没有找到满足条件的下标,返回false
  3. 为避免重复,j只需要遍历i之后的下标即可。
/**
 * @param {number[]} nums
 * @param {number} k
 * @param {number} t
 * @return {boolean}
 */
var containsNearbyAlmostDuplicate = function(nums, k, t) {
  // 遍历下标i
  for (let i = 0; i < nums.length; i++) {
    // 遍历下标j,j为i之后的所有下标
    for (let j = i + 1; j < nums.length; j++) {
      // 根据题意,查询是否存在满足条件的下标,有则返回true
      if (Math.abs(nums[i] - nums[j]) <= t && Math.abs(i - j) <= k) {
        return true;
      }
    }
  }

  // 如果正常退出循环,表示没有找到下标,返回false
  return false;
};
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