LeetCode-两数之和

文章目录

    • 题目链接
    • 题目描述
    • 示例
    • 解析
      • 解法一 暴力破解法
      • 解法一Java实现
      • 解法二 双重指针法。
      • 解法二Java实现
      • 解法三 hash法
      • 解法三Java实现

题目链接

Problem.1:https://leetcode-cn.com/problems/two-sum/description/

题目描述

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

示例

给定 nums = [2, 7, 11, 15], target = 9,因为 nums[0] + nums[1] = 2 + 7= 9,所以返回 [0, 1]

解析

解法一 暴力破解法

即采用二重循环,i作为第一层循环指针遍历数组,j=i+1作为第二层循环指针遍历数组,临时变量sum=i+j,当sum=target时,循环结束,返回结果。时间复杂度为o(n2),空间复杂度为o(1)。

解法一Java实现

public static int[] twoSum(int[] nums, int target) {
	int i,j,sum;
	int[] res = new int[2];
	for (i=0;ii && j

不出意外,被系统判定为超时。

解法二 双重指针法。

首先对数组排序,然后设定两个指针i和j,i指向数组的开始位置,j指向数组的结束位置,临时变量sum=i+j,sum小于target时i++,sum大于target时j–,sum等于target时结束,返回结果。时间复杂度o(nlogn),空间复杂度o(1)。

解法二Java实现

public int[] twoSum(int[] nums, int target) {
	int [] res = new int[2];
	int[] copylist = new int[nums.length];  
	System.arraycopy(nums, 0, copylist, 0, nums.length);  
	Arrays.sort(copylist);    
	int low = 0;
	int high = copylist.length-1;
	while(low < high){
		if(copylist[low] + copylist[high] < target){
			low++;
		} else if (copylist[low] + copylist[high] > target){
			high--;
		} else {
			res[0] = copylist[low];
			res[1] = copylist[high];
			break;
		}
	}
	int index1 = -1, index2 = -1;  
	for(int i = 0; i < nums.length; i++){  
		if(nums[i] == res[0] && index1 == -1){
				index1 = i+1;
		} else if(nums[i] == res[1] && index2 == -1){
			index2 = i+1; 
		}     
	} 
	res[0] = index1;
	res[1] = index2;
	Arrays.sort(res);
	return res;
}

解法三 hash法

利用HashMap的存取特性,以空间换时间。以数组下表作为key,数组值作为value,依次将nums数组存入map,同时判断target-nums[i]是否也存在于map,存在则退出,返回结果。时间复杂度o(n),空间复杂度o(n)。

解法三Java实现

public int[] twoSum(int[] nums, int target) {
	int[] res = new int[2];
	Map map = new HashMap();
	for(int i=0; i index2){
				res[0] = index2;
				res[1] = i;
			}
			break;
		}
		map.put(nums[i], i+1);
	}
	return res;
}

你可能感兴趣的:(数据结构与算法)