1. Two Sum - LeetCode

LeetCode Problems Solutions

question description: 问题描述

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

Thinking

基本排序算法中的选择排序是假定第0个为最小的,然后通过两次循环逐次比较(面试常见的基本排序算法)。我们也可以借助该思想,假定两个数中的第一个数是从第一个开始的,通过两次循环来获得两个数的索引。

solution with java - Java解决方案

public int[] twoSum(int[] nums, int target) {
        
        for (int i = 0; i < nums.length; i++){
            
            int first = nums[i];
            
            for ( int j = i + 1; j < nums.length ; j++){
                
                int secode = nums[j];
                
                if ( first + secode == target){

                    return new int[]{i,j};
                }
                
            }
              
        }
        
        return new int[]{0,0};
        
    }

solution with swift - swift解决方案

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        
        for i in 0 ..< nums.count  {
            
            let first = nums[i];
            
            for j in (i+1) ..< nums.count {
                
                let seconde = nums[j];
                
                if first + seconde == target {
                    
                    return [i,j];
                }
            }
            
        }
        return [0,0];
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Two Sum - LeetCode Question Given an array of integers...
    deactivateuser阅读 215评论 0 1
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,303评论 4 61
  • 忽然想起来一件很有意思的事。学院组织夏令营,一共四十个名额,两个导员负责组织,最后有20名学生向A导员报名,3...
    不知火玄奇阅读 208评论 0 0
  • 哦酷狗音乐弄
    东歌123阅读 105评论 0 0
  • 39号武丽娟感恩日志 1,感恩家人,每天幸福满满 2,感恩现在的生活多么幸福,路面下水管坏了,水哗哗的流,有些地方...
    花布鱼阅读 198评论 0 0