zoukankan      html  css  js  c++  java
  • 1. 两数之和(leetcode)

    解题思路:

    第一个方法是穷举,第二个方法是利用Map做,第二个方法一开始没想到,还是有点太年轻。

    代码:

    第一个代码:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] ans = new int[2];
            boolean flag = false;
            for(int i=0;i<nums.length;i++) {
                for(int j=0;j<nums.length;j++){
                    if(i == j){
                        continue;
                    }else{
                        if(nums[i] + nums[j] == target){
                            ans[0] = i;
                            ans[1] = j;
                            flag = true;
                            break;
                        }
                    }
                }
                if(flag){
                    break;
                }
            }
            
            
            return ans;
        }
    }

    第二个代码:

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> map = new HashMap<>();
            for(int i=0;i<nums.length;i++) {
                if(map.containsKey(target - nums[i])){
                    return new int[] {map.get(target - nums[i]),i};
                }
                map.put(nums[i], i);
            }
            return new int[1];
        }
    }
  • 相关阅读:
    提升ASP.NET性能
    人性的弱点
    墨菲定律
    沟通
    网站
    程序员思维模式
    CSS
    HTML
    路由和数据传递(04)
    Sql Server中查看所有数据库,表名,字段名以及字段类型
  • 原文地址:https://www.cnblogs.com/doubest/p/10467207.html
Copyright © 2011-2022 走看看