LeetCode刷题(二) —— Two Sum(一)

版本记录

版本号 时间
V1.0 2020.08.24 星期一

前言

很多技术大牛都刷过LeetCode,最近也看了一些,里面基本都是关于数据结构和算法的知识,感觉这个平台真的不错,就想着和大家一起分享。这个模块有很多是以前就刷过的,再次粘贴出来用来记录和分享。感兴趣接着看下面几篇。
1. LeetCode刷题(一) —— 前言(一)

题目描述

Two Sum源地址

下面看一下题目描述

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

这个题目的意思就是根据指定数组中任意两个元素等于给定的数组的元素的索引。


题目实现

1. C语言版本实现

下面是C语言版本的实现

#import <Foundation/Foundation.h>

static int a[2];

int* twoSum(int* nums, int numsSize, int target) {
    for(int i = 0; i < numsSize; i++){
        for(int j = i + 1; j<numsSize; j++ ){
            if(nums[i] + nums[j] == target){
                printf("%d--%d", i, j);
                a[0] = i;
                a[1] = j;
            }
        }
    }
    return a;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int a[4] = {2, 5, 11, 15};
        twoSum(a, 4, 16);
    }
    return 0;
}

下面看一下输出结果

1--2Program ended with exit code: 0

下面看一下一个网友给出的答案:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    
    int i, max, min;
    max = min = nums[0];
    for(i = 0; i < numsSize; i++) {
        if(nums[i] > max) max = nums[i];
        if(nums[i] < min) min = nums[i];
    }
    
    int *map   = (int*)calloc((max-min+1), sizeof(int));
    int *reval = (int*)malloc(sizeof(int)*2);
    
    for(i = 0; i < numsSize; map[nums[i]-min] = ++i) {
        int lookfornum = target - nums[i];
        if(lookfornum < min || lookfornum > max) continue;
        int dis = lookfornum - min;
        if (map[dis]) {         
            reval[0] = i;
            reval[1] = map[dis] -1;
            break;
        }
    }
    
    return reval;
}

后记

本篇主要讲述了题目Two Sum,感兴趣的给个赞或者关注~~~~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。