申请一个没交完,倒是开始刷题了
好久没写java 我竟然都不会写了
leetcode倒是不用写main哦
脑子里第一反应就是这个,暴力解法,我这个弱鸡
class Solution {
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){
return new int[]{i,j};
}
}
}
return null;
}
}
知识点:
- 要抛出异常:
答案里的 throw new IllegalArgumentException(“No two sum solution”); 是runtimeexception,是不用在方法里写throws声明的。
如果是自己写的异常,就要声明+try catch住
https://blog.csdn.net/jiaobuchong/article/details/47065563 - 然后感觉lc里面不好用自定义异常,因为总是要return语句
高级解法1: hash表,以空间换时间
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer>hash=new HashMap<>();
for(int i=0;i<nums.length;i++){
hash.put(nums[i],i);
}
for(int i=0;i<nums.length;i++){
int k=target-nums[i];
if(hash.containsKey(k)&&hash.get(k)!=i){
return new int[]{i,hash.get(k)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
高级解法2:一遍hash表,边初始化hash表边看有没有解
其实就是把两个for循环合并了
时间和空间复杂度都是没有变的
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer>hash=new HashMap<>();
for(int i=0;i<nums.length;i++){
int k=target-nums[i];
if(hash.containsKey(k)&&hash.get(k)!=i){
return new int[]{i,hash.get(k)};
}
hash.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}