zoukankan      html  css  js  c++  java
  • 求两个数之和

    求两个数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    int* twoSum(int* nums, int numsSize, int target, int* returnSize){
        int* res = (int *)malloc(sizeof(int) * 2);//申请动态空间
        for(int i = 0; i < numsSize-1; i++) {
            for(int j = i + 1; j < numsSize; j++) {
                if(nums[i] + nums [j] == target) {
                    res[0] = i;
                    res[1] = j;
                    *returnSize = 2;
                    return res;
                }
            }       
        }
        return res;
    }
    

    思路总结:这道题目的是从数组中找到和为一定数值的两个数,而最简单的思路就是将数组中所有的数,两两为一组一一列举出来,然后对其进行求和。进而找到我们需要的数字的下标,将其保存在一个数组中,返回。
    新增解法

    class Solution {
        public int[] twoSum(int[] nums, int target) {
          Map<Integer, Integer> map = new HashMap<>();//定义一个map
            for(int i = 0; i<nums.length;i++){//将数组中的值和下标存储到map中
                map.put(nums[i],i);
            }
            for(int i = 0;i<nums.length;i++){
                int tmp = target - nums[i];//如果已经存在了另一个数
                if(map.containsKey(tmp) && map.get(tmp) != i){//已经存在另外一个数且这个数不是自己
                    return new int[]{i,map.get(tmp)};
                }
            }
        
        }
    }
    
  • 相关阅读:
    451. Sort Characters By Frequency
    424. Longest Repeating Character Replacement
    68. Text Justification
    44. Wildcard Matching
    160. Intersection of Two Linked Lists
    24. Swap Nodes in Pairs
    93. 递归实现组合型枚举
    98. 分形之城
    97. 约数之和
    96. 奇怪的汉诺塔
  • 原文地址:https://www.cnblogs.com/mengxiaoleng/p/11373793.html
Copyright © 2011-2022 走看看