LeetCode----Two Sum

    xiaoxiao2022-06-29  47

    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.

    Example:

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

    UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully.

    public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { int index = map.get(numbers[i]); result[0] = index ; result[1] = i; break; } else { map.put(target - numbers[i], i); } } return result; } }

    int* twoSum(int* nums, int numsSize, int target) { int min = 2147483647; int i = 0; for (i = 0; i < numsSize; i++) { if (nums[i] < min) min = nums[i]; } int max = target - min; int len = max - min + 1; //确定hash长度 int *table = (int*)malloc(len*sizeof(int)); int *indice = (int*)malloc(2*sizeof(int)); for (i = 0; i < len; i++) { table[i] = -1; //hash初值 } for (i = 0; i < numsSize; i++) { if (nums[i]-min < len) { if (table[target-nums[i]-min] != -1) { //满足相加为target indice[0] = table[target-nums[i] - min]; indice[1] = i; return indice; } table[nums[i]-min] = i; } } free(table); return indice; }

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

    最新回复(0)