摘要: LeetCode第219题,Contains Duplicate II,使用Java语言的解题方案 自己写的: 思路:先将数组排序,然后一一比较数组的元素是否相等。 public class Solution { public bool ContainsDuplicate(int[] nums) { Array.Sort(nums); for(int i=0;i<nums.Length-1;i++) { if(nums[i]==nums[i+1]) { return true; } }
return false; } } 摘抄: 1、题目名称 Contains Duplicate II(判断数组内是否有重复元素2) 2、题目地址 https:///problems/contains-duplicate-ii/ 3、题目内容 英文: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 difference between i and j is at most k. 中文:给出一个整数数组,判断该数组内是否有两个元素值是相同的,且他们的索引值相差不大于k,是则返回true,否则返回false 4、一个TLE的方法 本题如果直接使用暴力方法解决会运行超时。一段TLE的Java代码如下:
5、解题方法1 一个比较容易想到的方式是使用HashMap来完成目标,使用HashMap解决本题的方式与解决第217题的方式(Contains Duplicate)非常类似。 Java代码如下:
6、解题方法2 另一种方式是使用HashSet来解决本问题。HashSet是使用HashMap实现的集合。在HashSet的add函数中,如果被插入的元素已存在,则返回true,否则返回false。下面的Java代码就是利用了HashSet的这个性质:
END 著作权归作者所有 |
|
来自: 雪柳花明 > 《LeetCode》