思路:
// @Title: 两数之和 (Two Sum)
// @Author: qisiii
// @Date: 2021-07-05 14:13:15
// @Runtime: 97 ms
// @Memory: 38.8 MB
// @comment:
// @flag:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
if(nums.length<0){return result;}
for(int i=0;i<nums.length;i++){
int cha=target-nums[i];
result[0]=i;
for(int j=0;j<nums.length;j++){
if(i==j){continue;}
if(cha==nums[j]){
result[1]=j;
return result;
}
}
}
return result;
}
}
+++ title = “两数之和 (Two Sum)” draft = false +++
思路:哈希
// @Title: 两数之和 (Two Sum)
// @Author: qisiii
// @Date: 2021-12-16 13:27:45
// @Runtime: 4 ms
// @Memory: 39.7 MB
// @comment: 哈希
// @flag: BLUE
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
HashSet set=new HashSet();
for (int num : nums) {
set.add(num);
}
for(int i=0;i<nums.length;i++){
int cha=target-nums[i];
if (set.contains(cha)){
for (int j = i+1; j < nums.length; j++) {
if (cha==nums[j]){
result[0]=i;
result[1]=j;
}
}
}
}
return result;
}
}
思路:2024年重新开始计算-两数之和暴力循环
// @Title: 两数之和 (Two Sum)
// @Author: qisiii
// @Date: 2024-04-10 21:30:50
// @Runtime: 55 ms
// @Memory: 43.6 MB
// @comment: 2024年重新开始计算-两数之和暴力循环
// @flag: RED
class Solution {
public int[] twoSum(int[] nums, int target) {
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;
}
}
+++ title = “两数之和 (Two Sum)” draft = false +++
思路:空间换时间,hashmap存储过往的key,检测target-num[i]是否存在
// @Title: 两数之和 (Two Sum)
// @Author: qisiii
// @Date: 2024-04-10 21:52:24
// @Runtime: 2 ms
// @Memory: 43.9 MB
// @comment: 空间换时间,hashmap存储过往的key,检测target-num[i]是否存在
// @flag: BLUE
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> old=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(old.keySet().contains(target-nums[i])){
return new int[]{i,old.get(target-nums[i])};
}else{
old.put(nums[i],i);
}
}
return null;
}
}
思路:暴力
// @Title: 两数之和 (Two Sum)
// @Author: qisiii
// @Date: 2021-12-16 13:25:46
// @Runtime: 33 ms
// @Memory: 38.6 MB
// @comment: 暴力
// @flag: BLUE
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
for(int i=0;i<nums.length;i++){
int cha=target-nums[i];
for (int j = i+1; j < nums.length; j++) {
if (cha==nums[j]){
result[0]=i;
result[1]=j;
}
}
}
return result;
}
}