zoukankan      html  css  js  c++  java
  • 1. 两数之和

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

    1. 暴力法:

    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* twoSum(int* nums, int numsSize, int target, int* returnSize){
        int i, j;
        int *result = (int *)malloc(2 * sizeof(int));
        for (i = 1; i < numsSize; i++)
        {
            for (j = 0; j < i; j++)
            {
                if (target - nums[i] == nums[j])
                {
                    result[0] = j;
                    result[1] = i;
                    *returnSize = 2;
                    return result;
                }
            }
        }
        return NULL;
    }

    执行用时: 76ms

    内存消耗: 6.2MB

    2. hash法

    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    #define SIZE 2000
    #define TWO 2
    int hash_tab[SIZE] = {0};

    int hash_get_key(int val)
    {
        int key;
        key = val % SIZE;
        if (key < 0)
        {
            key = key + SIZE;
        }
        return key;
    }

    int* twoSum(int* nums, int numsSize, int target, int* returnSize)
    {
        int *retnum = (int *)malloc(TWO * sizeof(int));
        for (int i = 0; i < SIZE; i++)
        {
            hash_tab[i] = INT_MAX;
        }
        for (int i = 0; i < numsSize; i++)
        {
            if (hash_tab[hash_get_key(nums[i])] != INT_MAX)
            {
                retnum[1] = i;
                retnum[0] = hash_tab[hash_get_key(nums[i])];
                *returnSize = 2;
                return retnum;
            }
            else
            {
                hash_tab[hash_get_key(target - nums[i])] = i;
            }
        }
        return NULL;
    }

    执行用时: 4ms

    内存消耗: 6.4MB

  • 相关阅读:
    Git: Host key verification failed(主机密钥验证失败)
    winrar 5.9.0 注册文件
    Intellij Idea开发: 手把手教你Java GUI开发,并且打包成可执行Jar程序
    axios 报 登出跨域 withCredentials: false,
    dist目录打war包命令 jar -cvf yourName_web.war *
    浅谈Dubbo服务
    PO BOX地址校验
    一次/etc/sudoers: syntax error near line 21问题的解决记录
    websocket+springboot原生
    自定义maven插件
  • 原文地址:https://www.cnblogs.com/arci/p/12467994.html
Copyright © 2011-2022 走看看