【LeetCode】1. Two Sum

原题网址:https://leetcode.com/problems/two-sum/

解题思路:

我的解:毫无疑问的暴力解。。。。这次暴力解出现问题了。。。就是[3,3] 6的时候我的解法会出现问题

public static int[] twoSum(int[] nums, int target) {
	        int l = nums.length;
	        int[] b = new int[l];
	        int j = 0;
	        int [] result = new int[2];
	        for(int i = 0; i < l; i++) {
	        	if(nums[i] > target) {
	        		continue;
	        	} else {
	        		b[j] = nums[i];
	        		j++;
	        	}
	        }
	        for(int i =0 ; i < j; i++) {
	        	for(int k = 0; k < j; k++) {
	        		if(b[i] == b[k]) {
	        			continue;
	        		} else {
	        			if((b[i] + b[k]) == target) {
	        				result[0] = i;
	        				result[1] = k;
	        				return result;
	        			}
	        		}
	        		
	        	}
	        }
	        return null;
	}

 最优解:

public int[] twoSum(int[] numbers, int target) {
    int[] result = new int[2];
//发现大神代码都这样定义一个返回结果的数组的。。。
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i + 1;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i + 1);
    }
    return result;
}

发现需要用到map集合,我对这部分不太熟悉。。过阵子再看吧。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值