Leetcode(一)两数之和

两数之和

暴力

双层循环 两两相加 等于目标值 返回 即可

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0;i<nums.length;i++){
            for(int j=0;j<nums.length;j++){
                if(nums[i]+nums[j]==target && i!=j){
                    int[] a={i,j};
                    return a;
                }
            }
        }
        return null;
    }
}

map

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map=new HashMap();
        int[] res=new int[2];
        for(int i=0;i<nums.length;i++){
            int a=target-nums[i];
            if(map.get(a)==null){
                map.put(nums[i],i);
            }else{
                res[0]=i;
                res[1]=map.get(a); 
            }
        }
        return res;
    }
}

快慢指针

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        //快速排序 O(nlogn)
        int[] copy=new int[nums.length];
        for(int t=0;t<nums.length;t++){
            copy[t]=nums[t];
        }
        Arrays.sort(nums);
        int[] res=new int[2];
        //快慢指针
        int j=nums.length-1;
        int i=0;
        while(i<nums.length){
            if(i==j)
            {
                return null;
            }
            if(nums[i]+nums[j]<target){
                i++;
            }else if(nums[i]+nums[j]>target){
                j--;
            }else{
                res[0]=i;
                res[1]=j;
                break;
            }
        }
        if(res[0]!=0||res[1]!=0){
            Boolean m=true;
            Boolean q=true;
            for(int k=0;k<nums.length;k++){
                if(copy[k]==nums[res[0]]&& m)
                {
                    res[0]=k;
                    m=false;
                }else if(copy[k]==nums[res[1]] && q)
                {
                    res[1]=k;
                    q=false;
                }
            }
        }
        return res;
    }
}

作者声明

handlebars 复制代码
如有问题,欢迎指正!
相关推荐
点云SLAM3 小时前
PyTorch 中.backward() 详解使用
人工智能·pytorch·python·深度学习·算法·机器学习·机器人
only-qi3 小时前
146. LRU 缓存
java·算法·缓存
xuxie135 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王5 小时前
Java中的多态有什么用?
java·后端
梁辰兴5 小时前
数据结构:排序
数据结构·算法·排序算法·c·插入排序·排序·交换排序
666和7775 小时前
Struts2 工作总结
java·数据库
中草药z5 小时前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
Lris-KK5 小时前
【Leetcode】高频SQL基础题--1731.每位经理的下属员工数量
sql·leetcode
野犬寒鸦5 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
zru_96025 小时前
centos 系统如何安装open jdk 8
java·linux·centos