LeetCode(35) Search Insert Position
来源:互联网 发布:人工智能 开源 编辑:程序博客网 时间:2024/04/28 07:03
递归版本 8ms
class Solution {public: void search(vector<int> &nums, int index1, int index2, int target, int &index, bool &doHave) { if(index1 > index2) return; if(index1 == index2) { if(nums[index1] == target) { doHave = true; index = index1; } return; } int mid = index1 + (index2 - index1) / 2; if(nums[mid] == target) { doHave = true; index = mid; return; } if(nums[mid] > target) search(nums, index1, mid - 1, target, index, doHave); if(nums[mid] < target) search(nums, mid + 1, index2, target, index, doHave); } int searchInsert(vector<int>& nums, int target) { int index; bool doHave = false; search(nums, 0, nums.size() - 1, target, index, doHave); if(doHave == false) { int i = 0; for(; i < nums.size(); ) if(nums[i] < target) i++; else break; return i; } return index; }};
迭代版本 8ms
class Solution {public: void search(vector<int> &nums, int index1, int index2, int target, int &index, bool &doHave) { if(index1 > index2) return; if(index1 == index2) { if(nums[index1] == target) { doHave = true; index = index1; } return; } int mid = index1 + (index2 - index1) / 2; if(nums[mid] == target) { doHave = true; index = mid; return; } if(nums[mid] > target) search(nums, index1, mid - 1, target, index, doHave); if(nums[mid] < target) search(nums, mid + 1, index2, target, index, doHave); } int searchInsert(vector<int>& nums, int target) { int index; bool doHave = false; //search(nums, 0, nums.size() - 1, target, index, doHave); int index1 = 0; int index2 = nums.size() - 1; while(index1 <= index2) { int mid = index1 + (index2 - index1) / 2; if(nums[mid] == target) { doHave = true; index = mid; break; } if(nums[mid] > target) { index2 = mid - 1; continue; } if(nums[mid] < target) { index1 = mid + 1; continue; } } if(doHave == false) { int i = 0; for(; i < nums.size(); ) if(nums[i] < target) i++; else break; return i; } return index; }};
0 0
- leetcode 35: Search Insert Position
- Leetcode(35) Search Insert Position
- [leetcode 35] Search Insert Position
- [Leetcode] 35 - Search Insert Position
- LeetCode 35 Search Insert Position
- leetcode-35 Search Insert Position
- LeetCode 35 Search Insert Position
- Leetcode 35 Search Insert Position
- Leetcode[35]-Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode-35-Search Insert Position
- leetcode 35 -- Search Insert Position
- leetcode[35]:Search Insert Position
- leetcode 35: Search Insert Position
- Leetcode#35 Search Insert Position
- LeetCode(35) Search Insert Position
- LeetCode 35: Search Insert Position
- Leetcode#35||Search Insert Position
- Could not publish server configuration for Tomcat v7.0 Server at localhost. Multiple Contexts have a
- JAVA 并发编程-线程范围内共享变量(五)
- ofbiz
- QImage与OpenCV中的MAT图像格式转换
- Spring scope
- LeetCode(35) Search Insert Position
- android数字签名
- Java 输入输出IO的学习【1】
- POJ 题目2506Tiling(大数)
- apicloud验证车牌号
- Lucene二(域选项、文档基本信息、索引的增删改查)
- UVA字符串的匹配与判断
- JAVA之BigInteger
- 【从零开始学NGUI 】 (二)Label