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

    https://leetcode-cn.com/problems/3sum/

    package 数组;
    
    import java.util.Arrays;
    import java.util.HashMap;
    
    public class 两数之和 {
    
        public static void main(String[] args) {
            int[] nums = {3, 2, 4};
            两数之和 两数之和 = new 两数之和();
            int[] result = 两数之和.twoSum(nums, 6);
            System.out.println(Arrays.toString(result));
        }
    
        // 方法一:暴力循环:target减去遍历到的数,去数组找另一个数
        public int[] twoSum(int[] nums, int target) {
            int[] result = new int[2];
            if (nums == null || nums.length == 0) {
                return null;
            }
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i], i);
            }
            for (int i = 0; i < nums.length; i++) {
                int other = target - nums[i];
                if (map.containsKey(other) && map.get(other) != i) {
                    result[0] = i;
                    result[1] = map.get(other);
                    return result;
                }
            }
            return null;
        }
    }
  • 相关阅读:
    1755:菲波那契数列
    1788:Pell数列
    3089:爬楼梯
    7832:最接近的分数
    7649:我家的门牌号
    7216:Minecraft
    7213:垃圾炸弹
    2983:谁是你的潜在朋友
    2723:因子问题
    2722:和数
  • 原文地址:https://www.cnblogs.com/guoyu1/p/15581951.html
Copyright © 2011-2022 走看看