1. 两数之和0001
class TwoSum0001 {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
res[0] = i;
res[1] = j;
break;
}
}
}
return res;
}
}
2. 整数反转0007
在java中 int32位最大值和最小值表示
Integer.MAX_VALUE;
Integer.MIN_VALUE
class Solution {
public int reverse(int x) {
int sum = 0;
boolean flag = false;
if (x < 0) {
flag = true;
x = Math.abs(x);
}
while (x != 0) {
if (sum > (Integer.MAX_VALUE - x % 10) / 10)
return 0;
sum = sum*10 + x % 10;
x /= 10;
}
return flag ? -sum : sum;
}
}
3. 回文数0009
x==y 是一个判断语句,如果x和y相等,就会返回一个true值,否则返回一个false。所以可以直接 return x == y。
public class PalindromeNumber0009 {
public boolean isPalindrome(int x) {
int y = 0;
int get = x;
boolean flag = false;
if (x < 0)
return flag;
while (x != 0) {
y = y*10 + x%10;
x /= 10;
}
if (y == x)
flag = true;
return flag;
}
4. 移除元素0027
思考问题的时候,如果比较相同行不通,那就试一试比较不同的时候,要学会变通。(注释的是超时了)
package com.lxh.simple;
//public class RemoveElement0027 {
// public int removeElement(int[] nums, int val) {
// int sum = nums.length;
// int tag = 0;
// for (int i = tag; i < nums.length; tag++) {
// if (nums[i] == val) {
// sum--;
// tag = i;
// for (int j = i; j < sum; j++) {
// nums[j] = nums[j+1];
// }
// nums[sum] = 0;
// }
// }
// return sum;
// }
//}
public class RemoveElement0027 {
public int removeElement(int[] nums, int val) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[j] = nums[i];
j++;
}
}
return j;
}
}
5. 加一0066
不要把问题复杂化,先捋清他们之间有什么关系。比如此题,一旦有位置不是9,则直接加1即可输出数组。一旦有位置为9则,则改位置变为0继续循环下去查找。
package com.lxh.simple;
import java.util.Arrays;
//
public class PlusOne0066 {
public int[] plusOne(int[] digits) {
for (int i = digits.length-1; i >= 0 ; i--) {
if (digits[i] != 9) {
digits[i] ++;
return digits;
}
digits[i] = 0;
}
int[] nums = new int[digits.length+1];
nums[0] = 1;
return nums;
}
public static void main(String[] args) {
int here[] = {9,9,9};
PlusOne0066 po = new PlusOne0066();
here = po.plusOne(here);
//打印数组要用Arrays.toString()方法,数组继承了object类的toString方法,数组类型将按照旧的格式打印。要想打印数组,就要调用静态方法Arrys.toString
System.out.println(Arrays.toString(here));
}
}
// public int[] plusOne(int[] digits) {
// int[] nums = new int[digits.length+1];
// int r = digits.length-1;
// int flag = 0;
// if (digits[r] + 1 > 9) {
// digits[r] = 0;
// flag = 1;
// for (int i = r-1; i >=0 ; i--) {
// if (flag != 0) {
// if (digits[i] + flag > 9) {
// digits[i] = 0;
// flag = 1;
// } else {
// digits[i] += 1;
// flag = 0;
// }
// }
// break;
// }
// } else {
// digits[r] += 1;
// return digits;
// }
// if (flag == 1) {
// for (int i = r+1; i > 0; i--) {
// nums[i] = digits[i-1];
// }
// nums[0] = 1;
// return nums;
// }
// return digits;
// }
//
// public static void main(String[] args) {
// int here[] = {9,9,9};
//
// PlusOne0066 po = new PlusOne0066();
// System.out.println(po.plusOne(here));
// }
//
6. x的平方根0069
package com.lxh.simple;
public class Sqrt0069 {
public int mySqrt(int x) {
int l=0, r=x, ans = -1;
while (l <= r) {
// 二分查找求中间值时更好的写法
int mid = l + (r - l) / 2;
if ((long)mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
public static void main(String[] args) {
Sqrt0069 sq = new Sqrt0069();
System.out.println(sq.mySqrt(245464161));
}
}
7. 罗马数字转整数0013
1、s.charAt(i),返回字符串指定索引处的 char 值。
2、s.replace();
该方法的作用是替换字符串中所有指定的字符,然后生成一个新的字符串,例如:
String s = “abcat”;
String s1 = s.replace(‘a’,‘1’);
该代码的作用是将字符串s中所有的字符a替换成字符1,生成的新字符串s1的值是“1bc1t”,而字符串s的内容不发生改变。如果需要将字符串中某个指定的字符串替换为其它字符串,则可以使用replaceAll方法,例如:
String s = “abatbac”;
String s1 = s.replaceAll(“ba”,“12”);
该代码的作用是将字符串s中所有的字符串“ab”替换为“12”,生成新的字符串“a12t12c”,而字符串s的内容也不发生改变。
package com.lxh.simple;
public class RomanToInteger0013 {
public int romanToInt(String s) {
s = s.replace("IV", "a");
s = s.replace("IX", "b");
s = s.replace("XL", "c");
s = s.replace("XC", "d");
s = s.replace("CD", "e");
s = s.replace("CM", "f");
int sum = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
sum += table(s.charAt(i));
}
return sum;
}
public int table(char s) {
switch (s) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
case 'a': return 4;
case 'b': return 9;
case 'c': return 40;
case 'd': return 90;
case 'e': return 400;
case 'f': return 900;
}
return 0;
}
public static void main(String[] args) {
RomanToInteger0013 rti = new RomanToInteger0013();
int r = rti.romanToInt("IX");
System.out.println(r);
}
}
总结:从本题中学会repalce,replaceAll的巧妙使用之处,同时更进一步掌握switch case的使用。
8. 十进制整数的反码1009
package com.lxh.simple;
/* 已通过 2021.9.29
*
* */
public class ComplementInteger1009 {
public int bitwiseComplement(int n) {
// 0在计算机中也分为+0和-0 这设计到更细节的东西
// 我们按照通常的理解做题就可以
if (n == 0)
return 1;
StringBuilder result = new StringBuilder();
while (n != 0) {
result.append(n%2);
n = n / 2;
}
result = result.reverse();
int length = result.length();
int[] nums = new int[length];
for (int i = 0; i < length; i++) {
nums[i] = result.charAt(i) == '1' ? 0 : 1;
}
int j = length-1;
int count = 1;
int sum=0;
while (j >= 0) {
nums[j] *= count;
count *= 2;
sum += nums[j];
j--;
}
return sum;
}
public static void main(String[] args) {
ComplementInteger1009 ci = new ComplementInteger1009();
System.out.println(ci.bitwiseComplement(112451214));
}
}
PS:
String s = Integer.toBinaryString(n);
将正整数N用二进制表示并转换为一个String类型的值s;
大神方案:
拿到题目先不要急,注意观察。
示例1:
输入:5 101
输出:2 010
所以本质是 111(7) - 101(5) = 010(2)
问题转化为:求输入数字N的二进制数长度
求得N的二进制数长度length后,就可以用长为length,各位均为1的数字减去N,即可得到最终结果
由于是二进制,所以可以使用 (int) log2(N) + 1来求其长度
比如5(101)的计算结果为:
(int) log2(N) + 1 = 2 + 1 = 3
而长为length,各位均为1的二进制数字的大小是 2 ^ length - 1
比如111 的大小即为 2^3 - 1 = 7
所以最终结果便是 2 ^ length - 1 - N
class Solution {
public int bitwiseComplement(int N) {
//对于0需要单独讨论,因为log(x) 的定义域不包括0
if(N == 0) return 1;
//java中没有log2(x)函数,默认log以e为底,log10以10为底
//所以要用换底公式loga(x) / loga(y) = logy(x)
//所以loge(N) / loge(2) = log2(N)
int length = (int)(Math.log(N) / Math.log(2)) + 1;
return (int)(Math.pow(2, length)) - 1 - N;
}
}
9. 二进制求和
package com.lxh.simple;
/* 已通过
* 题目:二进制求和
*
* 给你两个二进制字符串,返回它们的和(用二进制表示)。
* 输入为 非空 字符串且只包含数字 1 和 0。
*
* */
public class AddBinary0067 {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0) {
int getA = i >= 0 ? a.charAt(i--) - '0' : 0;
int getB = j >= 0 ? b.charAt(j--) - '0' : 0;
int sum = getA + getB +carry;
carry = sum >= 2 ? 1 : 0;
sum = sum >= 2 ? sum - 2 : sum;
result.append(sum);
}
if (carry == 1)
result.append(1);
return result.reverse().toString();
}
public static void main(String[] args) {
AddBinary0067 ab = new AddBinary0067();
System.out.println(ab.addBinary("1010", "1011"));
}
}
10. 两数之和II - 输入有序数组
package com.lxh.simple;
/* 已通过 但是时间复杂度和空间复杂度太高了
* 后面附上大神代码
*
*
* */
import java.util.Arrays;
public class TwoSumII0167 {
public int[] twoSum(int[] numbers, int target) {
int length = numbers.length;
int flag = 1;
int value = 0;
int[] get = new int[2];
for (int i = 0; i < length; i++) {
if (flag == 1) {
value = target - numbers[i];
for (int j = numbers.length - 1; j >= 0; j--) {
if (numbers[j] == value) {
get[0] = i+1;
get[1] = j+1;
flag = 0;
break;
}
}
} else {
break;
}
}
return get;
}
public static void main(String[] args) {
TwoSumII0167 twii = new TwoSumII0167();
int array[] = {2,7,11,15};
System.out.println(Arrays.toString(twii.twoSum(array,9)));
}
}
// 大神代码
/*
class Solution {
public int[] twoSum(int[] numbers, int target) {
int low = 0,high = numbers.length-1;
while(low
11. 只出现一次的数字
package com.lxh.simple;
/* 已通过 2021.9.29
* 执行用时和内存消耗有点不太理想
*
* 题解是用的位运算的 异或
*
*
* */
import java.util.Arrays;
public class SingleNumber0136 {
public int singleNumber(int[] nums) {
int i;
//java中自带的排序
Arrays.sort(nums);
for (i = 0; i < nums.length-1; i += 2) {
if (nums[i] != nums[i+1]) {
break;
}
}
return nums[i];
}
public static void main(String[] args) {
SingleNumber0136 sn = new SingleNumber0136();
int arrays[] = {4,1,2,1,4};
System.out.println(sn.singleNumber(arrays));
}
}
/*class Solution {
public int singleNumber(int[] nums) {
int reduce = 0;
for (int num : nums) {
reduce = reduce ^ num;
}
return reduce;
}
}*/
12. 搜索插入位置
package com.lxh.simple;
/* 已通过 用时0ms 内存消耗38.1M 稍微大了点
*
*
*
* */
public class SearchInsert0035 {
public int searchInsert(int[] nums, int target) {
int i = 0;
int j = nums.length - 1;
int middle = 0;
while (i <= j) {
middle = (i+j) / 2;
if (target > nums[middle]) {
i = middle + 1;
}else if (target < nums[middle]) {
j = middle - 1;
}else {
return middle;
}
}
return j + 1;
}
public static void main(String[] args) {
SearchInsert0035 si = new SearchInsert0035();
int arrays[] = {1};
System.out.println(si.searchInsert(arrays, 0));
}
}
13. 存在重复元素
package com.lxh.simple;
/* 已通过
*
* */
import java.util.Arrays;
public class ContainsDuplicate0217 {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i+1])
return true;
}
return false;
}
}
14. 各位相加
package com.lxh.simple;
/* 已通过
*
*
* */
public class AddDigits0258 {
public int addDigits(int num) {
while (num / 10 != 0) {
num = cycle(num);
}
return num;
}
public int cycle(int num) {
int sum = 0;
int get;
while (num != 0) {
get = num % 10;
num = num / 10;
sum += get;
}
return sum;
}
public static void main(String[] args) {
AddDigits0258 ad0258 = new AddDigits0258();
System.out.println(ad0258.addDigits(15254));
}
}
/* 大神代码 内存消耗低
*
* */
/*
class Solution {
public int addDigits(int num) {
return 1+(num-1)%9;
}
}*/
15. 移动零
package com.lxh.simple;
/* 已通过 但是执行时间和内存消耗很不理想
* 一定要学会正反思维方式,但计算谁是0比较麻烦时,可以直接考虑不是0的是谁。
*
* */
import java.util.Arrays;
public class MoveZeroes0283 {
public void moveZeroes(int[] nums) {
int count = nums.length;
int i, j;
for (i = 0; i < count; ) {
if (nums[i] == 0) {
for (j = i; j < nums.length-1; j++) {
nums[j] = nums[j+1];
}
nums[j] = 0;
count--;
} else
i++;
}
System.out.println(Arrays.toString(nums));
}
public static void main(String[] args) {
MoveZeroes0283 mz0283 = new MoveZeroes0283();
int arrays[] = {0,1,0,3,12};
mz0283.moveZeroes(arrays);
}
}
/*
思路:设置一个index,表示非0数的个数,循环遍历数组,
如果不是0,将非0值移动到第index位置,然后index + 1
遍历结束之后,index值表示为非0的个数,再次遍历,从index位置后的位置此时都应该为0
public void moveZeroes(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[index] = nums[i];
index++;
}
}
for (int i = index; i < nums.length; i++) {
nums[i] = 0;
}
} */
16. 最长公共前缀
package com.lxh.simple;
public class LongestCommon0014 {
public String longestCommonPrefix(String[] strs) {
//StringBuilder result = new StringBuilder();
String s = strs[0];
for (int i = 0; i < strs.length; i++) {
while (!strs[i].startsWith(s)) {
if (s.length() == 0)
return "";
s = s.substring(0, s.length()-1);
}
}
return s;
}
public static void main(String[] args) {
LongestCommon0014 lc0014 = new LongestCommon0014();
String strs[] = {"flower","flow","flight"};
System.out.println(lc0014.longestCommonPrefix(strs));
}
}
/*startsWith(String str)
startsWith(String str,int Index)
字符串中是否包含这个指定的字符串
重载的方法是可以指定是否在指定的下标开始的位置
substring();
*/
/*
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0)return "";
//公共前缀比所有字符串都短,随便选一个先
String s=strs[0];
for (String string : strs) {
while(!string.startsWith(s)){
if(s.length()==0)return "";
//公共前缀不匹配就让它变短!
s=s.substring(0,s.length()-1);
}
}
return s;
}
}*/
PS:
startsWith(String str)
startsWith(String str,int Index)
字符串中是否包含这个指定的字符串
重载的方法是可以指定是否在指定的下标开始的位置
substring();
public String substring(int beginIndex, int endIndex)
第一个参数int为开始的索引,对应String数字中的开始位置,
第二个参数是截止的索引位置,对应String中的结束位置
1、取得的字符串长度为:endIndex - beginIndex;
2、从beginIndex开始取,到endIndex结束,从0开始数,其中不包括endIndex位置的字符
17. 有效的括号
Ps:学会栈
toCharArray();将字符串转换为字符数组。
package com.lxh.simple;
/* 已通过 同时要自己利用栈写出来。
* 当对字符串进行修改的时候,特别是字符串对象经常改变的情况下,需要使用 StringBuffer 和 StringBuilder 类。
*
* */
public class ValidParentheses0020 {
public boolean isValid(String s) {
/* //StringBuffer定义的字符串中buffer.repalce(start, end, str"");可以直接删除字符串或者替换为其他字符。
StringBuffer buffer = new StringBuffer(s);
//if (s.length() == 1)
// return false;
int count = 0;
while (count != s.length()) {
int get = target(buffer);
//int judge = get;
if (get == 0 || get == buffer.length())
return false;
else
get -= 1;
if (buffer.charAt(get) == '(' && buffer.charAt(get+1) != ')')
return false;
else if (buffer.charAt(get) == '[' && buffer.charAt(get+1) != ']')
return false;
else if (buffer.charAt(get) == '{' && buffer.charAt(get+1) != '}')
return false;
else {
buffer.replace(get, get+2, "");
count += 2;
}
}
return true;
}
//找出每次没有碰到右括号的左括号
public int target(StringBuffer s) {
int flag = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '{' || s.charAt(i) == '[' || s.charAt(i) == '(') {
flag++;
} else
break;
}
return flag;
}*/
//用栈实现
//这是ToCharArray( )的用法,将字符串对象中的字符转换为一个字符数组。
char[] chars = s.toCharArray();
if (chars.length % 2 == 1) {
return false;
}
//创建栈
char[] stack = new char[chars.length];
int nowIndex = 0;
//这个和foreach的for循环一样的,也就是遍历
//这里的for(char c:chars)就是定义一个遍历字符c,让它分别等于字符串数组chars里面的各个字符,
//然后执行下面的语句,当c被赋值为chars里面所有字符各一次后,就会退出这个循环.
for (char c : chars) {
if (c == '{' || c == '[' || c == '(') {
stack[nowIndex++] = c;
} else {
if (nowIndex <= 0) {
return false;
}
char tmp = stack[--nowIndex];
if ((tmp == '{' && c == '}')
|| (tmp == '[' && c == ']')
|| (tmp == '(' && c == ')')) {
} else {
return false;
}
}
}
return nowIndex == 0;
}
public static void main(String[] args) {
ValidParentheses0020 vp0020 = new ValidParentheses0020();
String s = "(){}}{";
System.out.println(vp0020.isValid(s));
}
}
18. 多数元素
package com.lxh.simple;
/* 已通过
*
*
* */
import java.util.Arrays;
public class MajorityElement0169 {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for (int i = 0; i < nums.length-1; i++) {
sum++;
if (nums[i] != nums[i+1] && sum > nums.length / 2) {
sum = i;
break;
} else if (nums[i] != nums[i+1] && sum <= nums.length / 2){
sum = 0;
}
}
return nums[sum];
}
public static void main(String[] args) {
MajorityElement0169 me = new MajorityElement0169();
int arrays[] = {2,2,1,1,1,2,2};
System.out.println(me.majorityElement(arrays));
}
}
19. 最大连续1的个数
不断开始简化代码
package com.lxh.simple;
public class MaxConsecutive0485 {
public int findMaxConsecutiveOnes(int[] nums) {
int flag = 0;
int count = 0;
int i;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (count <= i-flag) {
count = i - flag;
}
flag = i + 1;
}
}
if (nums[i-1] == 1) {
count = count > i-flag ? count : i-flag;
}
return count;
/*int maxCount=0,res=0;
for(int i=0;i< nums.length;i++){
if(nums[i]==1){
maxCount++;
}else {
res=res>=maxCount?res:maxCount;
maxCount=0;
}
}
return res>maxCount?res:maxCount;*/
}
public static void main(String[] args) {
MaxConsecutive0485 mc0485 = new MaxConsecutive0485();
int nums[] = {1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1};
System.out.println(mc0485.findMaxConsecutiveOnes(nums));
}
}
20. 删除有序数组中的重复项
package com.lxh.simple;
/* 已通过
* System.gc(); 垃圾回收,回收内存
*
* */
public class RemoveDuplicatesSortedArray0026 {
public int removeDuplicates(int[] nums) {
if (nums.length == 0)
return 0;
int temp = 0;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] != nums[i+1]) {
nums[temp++] = nums[i];
}
}
nums[temp] = nums[nums.length-1];
return temp+1;
}
public static void main(String[] args) {
RemoveDuplicatesSortedArray0026 rs0026 = new RemoveDuplicatesSortedArray0026();
int[] nums = {};
System.out.println(rs0026.removeDuplicates(nums));
}
}
21. 最后一个单词的长度
package com.lxh.simple;
/* 已通过 用时0ms 内存消耗还是有点大
*
*
* */
public class LengthLastWord0058 {
public int lengthOfLastWord(String s) {
int length = s.length();
int count = 0;
while (length != 0 && s.charAt(length - 1) == ' ') {
length -= 1;
}
for (int i = length-1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
count++;
} else
break;
}
return count;
}
public static void main(String[] args) {
LengthLastWord0058 llw0058 = new LengthLastWord0058();
String s1 = "Hello World";
String s2 = " fly me to the moon ";
String s3 = "";
String s4 = " we ";
System.out.println(llw0058.lengthOfLastWord(s4));
}
}
22. 最大子序和
贪心法的思想:
本题还可以利用贪心法来实现, 贪心的思想是: 从左向右迭代, 一个个数字加过去如果sum<0, 那说明加上它只会变得越来越小, 所以我们将sum置零后重新开始找子序串.
在迭代的过程中要注意, 我们需要用result来不断维持当前的最大子序和, 因为sum的值是在不断更新的, 所以我们要及时记录下它的最大值.
有一个注意点是: 有的朋友可能觉得当数组全是负数的时候可能会出现问题, 其实是没有问题的. 因为在sum不断遍历的过程中, 早已将最大值不断传给result, 即使sum一直是负数被不断置零也不用担心, result还是会记录下最大的那个负数.
package com.lxh.simple;
/* 已通过 需自己再写一遍
* 这种题目要找到规律解起来才会快 耐心分析题目
*
* */
public class MaximumSubarray0053 {
public int maxSubArray(int[] nums) {
int res = nums[0];
int sum = 0;
for (int num : nums) {
if (sum > 0)
sum += num;
else
sum = num;
res = Math.max(res, sum);
}
return res;
}
}
23. 2的幂
package com.lxh.simple;
/* 已通过 时间1ms 战胜100% 内存35.6M 战胜27.57%
*
*
*
* */
public class PowerTwo0231 {
public boolean isPowerOfTwo(int n) {
if (n == 0)
return false;
int temp = nums(n);
if (temp == 1)
return true;
return false;
}
private int nums(int n) {
int flag = 0;
if (n == 1) {
flag = 1;
}
else {
if (n % 2 == 0) {
n /= 2;
flag = nums(n);
}
}
return flag;
}
public static void main(String[] args) {
PowerTwo0231 pt0231 = new PowerTwo0231();
System.out.println(pt0231.isPowerOfTwo(-16));
}
}
//内存消耗最低代码
/*
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}*/
24. 丑数
package com.lxh.simple;
/* 已通过 时间1ms 击败100% 内存消耗35.6M 击败7.08%
*
*
* */
public class UglyNumber0263 {
public boolean isUgly(int n) {
if (n == 0)
return false;
if (n == 1)
return true;
int[] nums = {2,3,5};
int i;
for (i = 0; i < nums.length; i++) {
if (n == 1) {
return true;
}
if (n % nums[i] == 0) {
n /= nums[i];
i -= 1;
}
}
return false;
}
public static void main(String[] args) {
UglyNumber0263 un0263 = new UglyNumber0263();
System.out.println(un0263.isUgly(0));
}
}
25. 存在重复的元素II
HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。
更纤细的内容:HashSet
package com.lxh.simple;
/* 已通过 2021.10.12 时间18ms 击败89.85% 内存消耗 47.3MB 击败83.18%
*
*
* */
import java.util.HashMap;
import java.util.Map;
public class ContainsDuplicateII0219 {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> sameOrNot = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (sameOrNot.containsKey(nums[i]) && i - sameOrNot.get(nums[i]) <= k) {
return true;
} else
sameOrNot.put(nums[i], i);
}
return false;
}
public static void main(String[] args) {
ContainsDuplicateII0219 cdc0219 = new ContainsDuplicateII0219();
int[] nums = {1,2,3,1,2,3};
System.out.println(cdc0219.containsNearbyDuplicate(nums, 2));
}
}
/* HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int l=0,r=0;
Set set = new HashSet();
while (r < nums.length) {
if (r - l <= k) {
if (set.add(nums[r])) {
r++;
} else {
return true;
}
} else {
set.remove(nums[l++]);
}
}
return false;
}
}*/