1 class Solution {
2 public int[] twoSum(int[] nums, int target) {
3 Map<Integer,Integer> map=new HashMap<>();
4 for(int i=0;i<nums.length;i ){
5 int x=target-nums[i];
6 if(map.containsKey(x)){
7 return new int[] {map.get(x),i};
8 }
9 map.put(nums[i],i);
10 }
11 throw new IllegalArgumentException("No two sum solution");
12 }
13 }
14 }
15 }
输入: [1,3,5,6], 7
输出: 4
因为for循环可能导致无返回值时,可抛出异常解决。
输入: [1,3,5,6], 0
输出: 0
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
index=-1
last=0
try:
return nums.index(target)
except:
for i in range(len(nums)):
if target > nums[i]:
last =1
nums.insert(last,target)
return index if index > 1 else last
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,且同样的元素不能被重复利用。
输入: [1,3,5,6], 5
输出: 2
你可以假设数组中无重复元素。
示例 3:
本文由美洲杯赔率发布于计算机教程,转载请注明出处:【leetcode 简单美洲杯赔率:】第十一题 搜索插入