Leetcode Two Sum
LeetCode sum two
2023-09-11 14:20:59 时间
struct Node{ int index; int value; }; bool compare(Node a, Node b) { return a.value < b.value; } class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { int i = 0; int size = numbers.size(); int index2 = 0; vector<Node> nodes; vector<int> result; for(i = 0; i < size; i++){ Node temp; temp.index = i + 1; temp.value = numbers[i]; nodes.push_back(temp); } sort(nodes.begin(), nodes.end(), compare); for(i = 0; i < size - 1; i++){ index2 = bSearch(nodes, target - nodes[i].value, i + 1, size); if(index2 != -1){ if(nodes[i].index > nodes[index2].index){ result.push_back(nodes[index2].index); result.push_back(nodes[i].index); } else { result.push_back(nodes[i].index); result.push_back(nodes[index2].index); } break; } } return result; } int bSearch(vector<Node> &nodes, int target, int start, int end){ int mid = 0; while(start <= end){ mid = (start + end) >> 1; if(target < nodes[mid].value){ end = mid - 1; } else if (target > nodes[mid].value){ start = mid + 1; } else { return mid; } } return -1; } };
相关文章
- Java实现 LeetCode第30场双周赛 (题号5177,5445,5446,5447)
- Java实现 LeetCode 676 实现一个魔法字典(暴力)
- Java实现 LeetCode 590 N叉树的后序遍历(遍历树,迭代法)
- Java实现 LeetCode 587 安装栅栏(图算法转换成数学问题)
- Java实现 LeetCode 462 最少移动次数使数组元素相等 II
- Java实现 LeetCode 391 完美矩形
- Java实现 LeetCode 128 最长连续序列
- Java实现 LeetCode 4 寻找两个有序数组的中位数
- Java实现LeetCode_0009_PalindromeNumber
- 628. 三个数的最大乘积 ——【Leetcode每日一题】
- 【LeetCode 3】无重复字符的最长子串
- LeetCode 1. Two Sum
- Leetcode 2053. 数组中第 K 个独一无二的字符串
- [LeetCode] 39. Combination Sum ☆☆☆(数组相加等于指定的数)
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)
- [LeetCode] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)
- [LeetCode] 111. Minimum Depth of Binary Tree ☆(二叉树的最小深度)
- 【leetcode】 Permutation Sequence
- [Leetcode]-Min Stack
- LeetCode: Sum Root to Leaf Numbers [129]
- LeetCode 68 Text Justification
- 【Leetcode刷题Python】LeetCode 478. 在圆内随机生成点
- leetcode- 两数之和