码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode第一题

时间:2021-02-19 13:36:23      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:while   第一题   dex   port   一个   sum   etc   imp   使用   

题目描述:

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

 

示例:

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

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

Code:

import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;

public class 三数之和 {
public static void main(String[] args) {
int[] nums = {1, -1, -1, 0};
List<List<Integer>> result = threeSum(nums);
System.out.println(result.toString());
}

public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int len = nums.length;
if (null == nums || len < 3) {
return result;
} else {
Arrays.sort(nums);
for (int index = 0; index < len - 1; index++) {
if (index > 0 && nums[index] == nums[index - 1]) {
continue;
}
for (int leftPoint = index + 1, rightPoint = len - 1; leftPoint < rightPoint; ) {
int sum = nums[index] + nums[leftPoint] + nums[rightPoint];
if (sum < 0) {
leftPoint++;
} else if (sum > 0) {
rightPoint--;
} else {
result.add(Arrays.asList(nums[index], nums[leftPoint], nums[rightPoint]));
leftPoint++;
while (rightPoint > leftPoint && nums[rightPoint] == nums[rightPoint - 1]) {
rightPoint--;
}
while (leftPoint < rightPoint && nums[leftPoint - 1] == nums[leftPoint]) {
leftPoint++;
}
}
}
}
}
return result;
}
}
 

leetCode第一题

标签:while   第一题   dex   port   一个   sum   etc   imp   使用   

原文地址:https://www.cnblogs.com/liuxingcheng/p/14411150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!