L610 Two Sum VII - Difference equals to target
Given an array of integers, find two numbers that theirdifference
equals to a target value.
where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.
Notice
It's guaranteed there is only one available solution
Example
Given nums =[2, 7, 15, 24]
, target =5
return[1, 2]
(7 - 2 = 5)
这题得注意difference指的是abs,所以得算两个值。基本架构跟2sum一样,得用hashmap。在算diff的时候得注意是谁减谁。
如果不能用hashmap的话,如果是排序的,也可以用通向双指针做。先把target abs一下,保证是正数,然后比较像sliding window那样,先把右边移到差值比target大的,譬如,[2, 7, 15, 24] target = 8, i指向2,j移动到15,然后左边继续向右移,i指向7,然后就找到了。
Last updated