[LC]219题 Contains Duplicate II (存在重复元素 II )

①英文题目:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

②中文题目:

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

③思路:就是个判断过程而已,注意求绝对值的函数是Math.abs(),我的解法,速度太慢了,我看到别人的速度很快的答案,都是用的哈希表,或者官方解答里用的散列表的速度很快。我暂时还没学过哈希和散列,所以用不来。留待以后来用两者解题。

     注意&&是个短路型符号,我个人感觉先判断i与j只差,比判断nums[i]==nums[j]来的快,所以把前者写在&&前边。

④我的代码:

 1 class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3          boolean abc=false;
 4         labe: for(int i = 0; i < nums.length; i++){
 5              for(int j = i+1; j < nums.length; j++){
 6                   if(Math.abs(j-i)<=k&&nums[i]==nums[j]){
 7                       abc = true; 
 8                       break labe;
 9                   }
10              }
11         }
12         return abc;
13     }
14 }

猜你喜欢

转载自www.cnblogs.com/zf007/p/11520718.html