第一题
题目
给你一个整数数组 nums
。如果任一值在数组中出现 至少两次 ,返回 true
;如果数组中每个元素互不相同,返回 false
思路
1、我的思路-先排序,然后直接遍历,只要前一个元素等于后一个元素,直接返回true;不过这种方法时间复杂度和空间复杂度都不咋滴啊
2、还有暴力破解,两个for循环嵌套,也不太好
3、使用哈希
代码
第一种方法
public boolean containsDuplicate(int[] nums) {
if(nums.length == 1) return false;
Arrays.sort(nums);
boolean res = false;
for(int i = 0; i < nums.length - 1; i++) {
if(nums[i] == nums[i+1]) {
res = true;
break;
};
};
return res;
}
第三种方法
public boolean containsDuplicate(int[] nums) {
if(nums.length == 1) return false;
Set<Integer> setList = new HashSet<Integer>();
boolean res = false;
for(int i = 0; i < nums.length; i++) {
if(!setList.add(nums[i])) {
res = true;
break;
};
};
return res;
}
第二题
题目
给你一个整数数组 nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分
思路
寻找第i个位置的最大连续子数组
代码
import java.util.*;
class Solution {
public int maxSubArray(int[] nums) {
if(nums.length == 1) return nums[0];
int maxNum = 0;
int maxRes = nums[0];
for(int i : nums) {
// 如果i之前的元素最大和加上i还没有i大,直接舍弃前面的,取i就可以
maxNum = Math.max(maxNum + i, i);
maxRes = Math.max(maxNum, maxRes);
}
return maxRes;
}
}
第三题
题目
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案
思路
1、暴力破解
2、哈希
代码
暴力破解
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = {0,1};
for(int i = 0; i < nums.length -1; i++) {
int first = nums[i];
for(int j = nums.length -1; j > i; j--) {
if(target - first == nums[j]){
res[0] = i;
res[1] = j;
};
};
};
return res;
}
}
哈希
class Solution{
public int[] twoSum(int[] nums,int target){
Map <Integer , Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int temp = target-nums[i] ;
if (map.containsKey(temp)){
return new int [] {map.get(temp),i};
}
map.put(nums[i],i);
}
return new int[] {-1,-1};
}
}