Two Sum

leetcode的第一題,很簡單。數組

題目以下spa

Given an array of integers, return indices of the two numbers such that they add up to a specific target.rest

You may assume that each input would have exactly one solution, and you may not use the same element twice.code

Example:blog

  Given nums = [2, 7, 11, 15], target = 9,索引

  Because nums[0] + nums[1] = 2 + 7 = 9ci

  return [0, 1].element

時間複雜度爲O(n)的一種解法爲:leetcode

 1 int* twoSum(int* nums, int numsSize, int target) 
 2 {
 3     int index[100001] = {0}, *index_plus_one = index + 50000;//索引從index數組的第50000個元素開始,避免出現負數索引報錯;
 4     for (int i = 0; i < numsSize; i++) 
 5     {
 6         int rest = target - nums[i];
 7         if (index_plus_one[rest]) 
 8         {
 9             //若是rest這個索引已經計算過了,那麼就能夠得出答案
10             int *ans = malloc(sizeof(int) * 2);
11             ans[0] = i;
12             ans[1] = index_plus_one[rest] - 1;
13             return ans;
14         }
15         else
16             index_plus_one[nums[i]] = i + 1;//若是rest這個索引沒有計算過,那麼就將 index_plus_one[nums[i]] 標記爲大於0;
17     }
18     return NULL;
19 }
相關文章
相關標籤/搜索