LeetCode 1. Two Sum 找到两数字求和索引集合

 https://leetcode.com/problems/two-sum/description/

第一种方法  遍历查找

复制代码
//
//  main.m
//  HFCDemo
//
//  Created by HF on 2018/9/5.
//  Copyright © 2018年 HF. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 * Note: The returned array must be malloced, assume caller calls free().
 * int *array = (int *)malloc(sizeof(int) * 2);
 */
int* twoSum(int* nums, int numsSize, int target) {
    int oneIndex = 0;
    int twoIndex = 0;
    for (int i = 0;i < numsSize; i ++) {
        int one = nums[i];
        int two = target - one;
        for (int j = 0; j < numsSize; j ++) {
            if (j > i && nums[j] == two) {
                oneIndex = i;
                twoIndex = j;
                break;
            }
        }
    }
    //要求必须动态分配空间数组
    int *array = (int *)malloc(sizeof(int) * 2);
    array[0] = oneIndex;
    array[1] = twoIndex;
    return array;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!\n");
        int numSize = 4;
        int nums[4] = {2, 7, 11, 15};
        int target = 9;
        int *array = twoSum(nums, numSize, target);
        printf("%d %d\n",array[0],array[1]);
        free(array);
    }
    return 0;
}
复制代码

第二种:哈希

待完成

posted on   ACM_Someone like you  阅读(188)  评论(0编辑  收藏  举报

编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示