两数之和问题 hashmap版

上一篇的解法容易理解,采用了暴力求解法,但是时间复杂度是O(n^2),
这里,采用了HashMap的方法,时间复杂度是O(n),实际上就是通过HashMap去掉了一层for循环,通过空间换时间,空间复杂度为O(n)
可以参考我的上一篇文章,对照阅读 两数之和 两层for循环版

package SumOfTwoNum;

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

public class Solution2 {
	public static int[] hashFindTwoNum(int[] nums, int target) {
		int len = nums.length;
		//因为这里的最大长度为len-1
		//在这个map中,key表示具体的数,value表示标
		Map<Integer, Integer> map = new HashMap<Integer, Integer>(len - 1);
		for(int i = 0; i < len; i ++) {
			if(map.containsKey(target - nums[i])) {
				return new int[] {i, map.get(target - nums[i])};
			}
			//第一步就执行了
			map.put(nums[i], i);
		}
		throw new IllegalArgumentException("没有找到");
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入数组:(以逗号分隔开)");
		//获得输入的数组
		String str = sc.nextLine();
		//拆分
		String[] strs = str.split(",");
		int[] nums = new int[strs.length];
		//转化
		for(int i = 0; i < strs.length; i ++) {
			nums[i] = Integer.parseInt(strs[i]);
		}
		System.out.println("请输入目标数");
		int target = sc.nextInt();
		int[] solution = hashFindTwoNum(nums, target);
		System.out.println("找到的解为:" + "下标" + (solution[1] + 1) + "\t" + "下标" + (solution[0] + 1));
	}
}

运行截图

请输入数组:(以逗号分隔开)
2,35,4,6,15,23,88,41,25,
请输入目标数
19
找到的解为:下标3	下标5
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用哈希表来解决两数之和问题。哈希表是一种将键和值进行映射的数据结构,它可以快速地查找给定键对应的值。以下是一个使用哈希表求解两数之和的示例代码: ```c #include <stdio.h> #include <stdbool.h> typedef struct { int key; int value; } HashNode; typedef struct { HashNode** table; int size; } HashMap; HashMap* createHashMap(int size) { HashMap* hashMap = (HashMap*)malloc(sizeof(HashMap)); hashMap->size = size; hashMap->table = (HashNode**)malloc(sizeof(HashNode*) * size); for (int i = 0; i < size; i++) { hashMap->table[i] = NULL; } return hashMap; } void put(HashMap* hashMap, int key, int value) { int hash = abs(key) % hashMap->size; while (hashMap->table[hash] != NULL && hashMap->table[hash]->key != key) { hash = (hash + 1) % hashMap->size; } if (hashMap->table[hash] != NULL) { free(hashMap->table[hash]); } HashNode* node = (HashNode*)malloc(sizeof(HashNode)); node->key = key; node->value = value; hashMap->table[hash] = node; } int get(HashMap* hashMap, int key) { int hash = abs(key) % hashMap->size; while (hashMap->table[hash] != NULL && hashMap->table[hash]->key != key) { hash = (hash + 1) % hashMap->size; } if (hashMap->table[hash] == NULL) { return -1; } else { return hashMap->table[hash]->value; } } bool containsKey(HashMap* hashMap, int key) { int hash = abs(key) % hashMap->size; while (hashMap->table[hash] != NULL && hashMap->table[hash]->key != key) { hash = (hash + 1) % hashMap->size; } return hashMap->table[hash] != NULL; } void freeHashMap(HashMap* hashMap) { for (int i = 0; i < hashMap->size; i++) { if (hashMap->table[i] != NULL) { free(hashMap->table[i]); } } free(hashMap->table); free(hashMap); } int* twoSum(int* nums, int numsSize, int target, int* returnSize) { HashMap* hashMap = createHashMap(numsSize); for (int i = 0; i < numsSize; i++) { int complement = target - nums[i]; if (containsKey(hashMap, complement)) { int* result = (int*)malloc(sizeof(int) * 2); result[0] = get(hashMap, complement); result[1] = i; *returnSize = 2; freeHashMap(hashMap); return result; } put(hashMap, nums[i], i); } freeHashMap(hashMap); return NULL; } int main() { int nums[] = {2, 7, 11, 15}; int target = 9; int returnSize; int* result = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize); if (result != NULL) { printf("Indices: %d, %d\n", result[0], result[1]); free(result); } else { printf("No solution found.\n"); } return 0; } ``` 这段代码的思路是使用哈希表来存储每个元素的值和索引,然后遍历数组中的每个元素,查找是否存在与当前元素值相加等于目标值的另一个元素。如果存在,则返回这两个元素的索引。否则,返回NULL表示没有找到解决方案。 希望这可以帮助到你!如有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值