LetCode-面试经典算法(java实现)【LetCode001: two Sum】

一、题目描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

二、解题思路

我的第一感觉就是用暴力法,简单直接。在一个数组中找到二个数字,它们的和为目标值的和。二重循环,只要第二重循环中只要存在target-nums[i]的数值,而且此值的下标不为i。返回这二个值(i , target-nums[i]的下标)。但是此解法的时间复杂度为O(n^2)。

有一种时间复杂度比较低一点的,用哈希表,整体思想也是和暴力类类似。将数组表示的数据,用哈希表表示,将数据的值和下标联系起来,循环遍历数组的每一个元素,然后查看哈希表中是否存在target-nums[i]的数值且此值的下标不为i。

还有一种更优秀一点的思想。同样是用哈希表,不过只遍历一次数组。每取一个nums[i],就判断target-nums[i]是不是再哈希表中,当然一开始哈希表中的数值为空。如果有就返回二个值的下标。没有执行下一个操作,将nums[i]加入到和哈希表中。

三、代码实现

package com.acm.Secondmonth;

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

public class LetCode001 {
	
	public static void main(String[] args) {
		int[] num = {3,3};
		int target = 6;
		int[] index = new int[2];
		index = twoSum03(num , target);
		for (int i : index) {
			System.out.println(i);
		}
	}

	private static int[] twoSum(int[] num, int target) {
		int[] index = new int[2];
		for(int i=0 ; i<num.length ; i++) {
			index[0] = i;
			for(int j=i ; j<num.length ; j++) {
				if(target - num[i] == num[j]) {
					index[1] = j;
					return index;
				}
			}
		}
		return null;
	}
	
	private static int[] twoSum01(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];
			//和暴力法不同就是map有自带的函数 看是不是包含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!");
	}
	/**
	 * 一次遍历
	 * @param nums
	 * @param target
	 * @return
	 */
	public static int[] twoSum03(int[] nums, int target) {
		if(nums == null) {
			throw new RuntimeException("invaild input:nums is empty!");
		}
		Map<Integer, Integer> map = new HashMap<>();
		for(int i=0 ; i<nums.length ; i++) {
			int complement = target - nums[i];
			System.out.println(complement + " " + map.get(complement) + " " + nums[i]);
			if(map.containsKey(complement) && map.get(complement) != i) {
				return new int[]{i , map.get(complement)};
			}
			map.put(nums[i], i);
		}
		throw new IllegalArgumentException("No two sum solution!");
	}
}

作者:Rusian_Stand 
来源:CSDN 
原文:https://blog.csdn.net/Vpn_zc/article/details/84072492 
版权声明:本文为博主原创文章,转载请附上博文链接!

发布了14 篇原创文章 · 获赞 1 · 访问量 5528

猜你喜欢

转载自blog.csdn.net/Vpn_zc/article/details/84072492