zoukankan      html  css  js  c++  java
  • 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!
    ");
            int numSize = 4;
            int nums[4] = {2, 7, 11, 15};
            int target = 9;
            int *array = twoSum(nums, numSize, target);
            printf("%d %d
    ",array[0],array[1]);
            free(array);
        }
        return 0;
    }

    第二种:哈希

    待完成

  • 相关阅读:
    雨中梦游
    最后一次为你哭
    poj3169 Layout
    poj2253 Frogger
    钟爱一生
    POJ2668解题报告
    魅力泸西
    android学习笔记09(activity的生命周期)
    poj 3468 A Simple Problem with Integers
    android学习笔记之多线程(二)
  • 原文地址:https://www.cnblogs.com/someonelikeyou/p/9595637.html
Copyright © 2011-2022 走看看