两数之和的一题多解

package practice;import java.util.HashMap;import java.util.Map;public class Ecercise1两数之和 { public static void main(String[] args) { }}class Solution { public int[] twoSum(int[] nums, in...
摘要由CSDN通过智能技术生成
package practice;

import java.util.HashMap;
import java.util.Map;

public class Ecercise1两数之和 {

	public static void main(String[] args) {

	}

}

class Solution {
	public int[] twoSum(int[] nums, int target) {
		// 暴力求解①时间和内存占用过高
		int[] temp = new int[2];// 用来存储那两个整数的下标
		int[] num = new int[nums.length];// 复制数组
		boolean is = false;
		System.arraycopy(nums, 0, num, 0, nums.length);
		for (int i = 0; i < num.length; i++) {
			for (int j = 0; j < num.length; j++) {
				if (nums[i] + nums[j] == target && i != j) {
					temp[0] = i;
					temp[1] = j;
					is = true;// 用来跳出外层循环
					break;
				}
			}
			if (is) {
				break;
			}
		}
		return temp;
	}

	// 暴力求解②时间和内存占用比①要少
	public int[] twoSum2(int[] nums, int target) {
		for (int i = 0; i < nums.length; i++) {
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[j] == target - nums[i]) {
					return new int[] { i, j };
				}
			}
		}
		// 抛出的异常表明向方法传递了一个不合法或不正确的参数。
		// 和try{}catch{}一样,也是java的一种异常捕获机制
		throw new IllegalArgumentException("No two sum solution");
	}

	// 两遍遍历哈希表③比暴力求解②时间和内存占用更少
	public int[] twoSum3(int[] nums, int target) {
		Map<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 complement = target - nums[i];
			if (map.containsKey(complement) && map.get(complement) != i) {
				return new int[] { i, map.get(complement) };
			}
		}
		throw new IllegalArgumentException("No two sum solution");
	}

	// 一遍遍历哈希表④和暴力求解②差不多
	public int[] twoSum4(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			int complement = target - nums[i];
			if (map.containsKey(complement)) {
				return new int[] { map.get(complement), i };
			}
			map.put(nums[i], i);
		}
		throw new IllegalArgumentException("No two sum solution");
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值