Two Sum
来源:互联网 发布:鲁滨逊漂流记java 编辑:程序博客网 时间:2024/05/17 09:47
Given an array of integers, find how many unique pairs
in the array such that their sum is equal to a specific target number. Please return the number of pairs.
Example
Given nums = [1,1,2,45,46,46]
, target = 47
return 2
1 + 46 = 47
2 + 45 = 47
java
public class Solution { /* * @param nums: an array of integer * @param target: An integer * @return: An integer */ public int twoSum6(int[] nums, int target) { // write your code here if (nums == null || nums.length == 0 || nums.length == 1) { return 0; } int left = 0; int right = nums.length - 1; int value = 0; int count = 0; Arrays.sort(nums); while (left < right) { value = nums[left] + nums[right]; if (left < right && value < target) { left++; } if (left < right && value > target) { right--; } if (left < right && value == target) { count++; left++; right--; while (left < right && nums[left] == nums[left - 1]) { left++; } while (left < right && nums[right] == nums[right + 1]) { right--; } } } return count; }}
python
class Solution: """ @param: nums: an array of integer @param: target: An integer @return: An integer """ def twoSum6(self, nums, target): # write your code here if nums == None or len(nums) == 0 or len(nums) == 1: return 0 left, right, value, count = 0, len(nums) - 1, 0, 0 nums.sort() while left < right: value = nums[left] + nums[right] if left < right and value < target: left += 1 if left < right and value > target: right -= 1 if left < right and value == target: count += 1 left += 1 right -= 1 while left < right and nums[left] == nums[left - 1]: left += 1 while left < right and nums[right] == nums[right + 1]: right -= 1 return count
阅读全文
0 0
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 一个简单的java缓存类
- 141. Linked List Cycle
- 尝试用es6封装方法
- Spring MVC——基础(简介,使用,地址映射)
- 【Leetcode-Medium-46】Permutations
- Two Sum
- The C Programming Language 练习题4-5
- 合并两个链表,两个表的元素交叉进行,合并之后合并后的链表变成空表
- Numpy混淆点理解
- PullToRefresh
- php实现redis消息队列将数据保存到mysql
- 1039. 到底买不买(20)
- 【OpenCV】error C4996: 'fopen': This function or variable may be unsafe
- 安卓无线调试 react-native