leetcode练习-简单题-两数之和

import java.util.Arrays;

public class App {
    public static void main(String[] args) throws Exception {
        Solution a = new Solution();
        int nums[] = { 1, 2, 3, 4 };
        a.twoSum(nums, 6);
        String stringLikeArray = Arrays.toString(a.result);
        System.out.println(stringLikeArray);
    }
}

class Solution {
    int result[] = new int[2];

    public int[] twoSum(int[] nums, int target) {
        int i, j;
        for (i = 0; i < nums.length; i++) {
            for (j = i + 1; j < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }
}
// mark一下,leetcode的第一道题目,这道题需要双循环进行遍历,则设置两个变量就好了,很久没碰过java了,所以真的挺多东西都忘了,甚至数组的new都忘了
// 数组不是显示类,但也是继承object的对象
// Arrays需要先引用才能使用

哈希表做法

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> table = new HashMap();
        int[] res = new int[2];
        //把数组中的数按照<key, value>存入表中
        //!!<nums[i], index> = <key, value>
        //用target-遍历nums的最新的那个数;
        //contains方法查看是否有对应的数在hash表,有就返回key
        //没有就put进去
        for(int i = 0; i < nums.length; i++){
            if(table.containsKey(target - nums[i])){
                res[0] = table.get(target - nums[i]);
                res[1] = i;
                return res;
            }
            table.put(nums[i], i);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值