1. Two Sum

xiaoxiao2021-02-28  97

题目:

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].

想法

对nums建立hash表,再遍历nums,看hash表中有没有相对应的关键字加上num会等与target

代码int* twoSum(int* nums, int numsSize, int target) { int min = nums[ 0 ], max = nums[ 0 ]; int *arr = malloc( sizeof( int ) * 2 ); for( int i = 1; i < numsSize; i++ ) { if( min > nums[ i ] ) { min = nums[ i ]; } if( max < nums[ i ] ) { max = nums[ i ]; } } int *hash = malloc( sizeof( int ) * ( max - min + 1 ) ); for( int i = 0; i < max - min + 1; i++ ) { hash[ i ] = -1; } for( int i = 0; i < numsSize; i++ ) { int key = target - nums[ i ] - min; if( key < 0 || key >= max - min + 1) { continue; } if( hash[ key ] >= 0 ) { arr[ 0 ] = i; arr[ 1 ] = hash[ key ]; free( hash ); return arr; } hash[ nums[ i ] - min ] = i; } free( hash ); return arr; }

转载请注明原文地址: https://www.6miu.com/read-66691.html

最新回复(0)