Leetcode
Contains Duplicate
Question
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Analysis
利用hash表,将数组中的元素逐个插入hash表中,当遇到第一个重复不可插入的时候返回false,否则返回true
Code
|
|
Summary
一开始很蠢的先查看s内是否contain再插入,这样的话会报exceed time limits
的错误,所以直接看是否能add即可
Contains Duplicate II
Question
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.
Analysis
由于java中的set中没有脚标,故没有办法进行脚标的对比,所以选择hash中的map对脚标进行记录
Code
|
|
Contains Duplicate III
Question
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
Analysis
维持一个长度为k的窗口,每次检查新加入的值与窗口内其他的值是否差值有小于等于t的。但是如果嵌套的两个for循环,则会超时。利用Java中的Treeset、subSet查看是否有处于范围大小内的记录即可,复杂度为 O(n logk)
Code
|
|
TreeSet/SubSet
TreeSet
TreeSet是集合,是用来存数据的,就像数组一样,但TreeSet是动态的。
TreeSet存的数据是无序号的,你不能通过get的方法获得里面的数据。
TreeSet存数据是有顺序的,这个顺序是你规定的,规定方法就是通过实现Comparator接口.
SubSet
Code
|
|
Output
|
|
Code
|
|
Output
|
|