admin管理员组文章数量:1026989
LeetCode
力扣链接
数组在内存中的空间地址是连续的
//
// Created by lwj on 2022-03-30.
//
#include <iostream>using namespace std;
void test_arr() {int array[2][3] = {{0, 1, 2},{3, 4, 5}};cout << &array[0][0] << " " << &array[0][1] << " " << &array[0][2] << endl;cout << &array[1][0] << " " << &array[1][1] << " " << &array[1][2] << endl;
}int main() {test_arr();
}
// 输出结果为0x61fdd0 0x61fdd4 0x61fdd8
// 0x61fddc 0x61fde0 0x61fde4 可以看出数组的内存空间的地址是连续的,所以我们在删除或者增添元素的时候,就需要移动其他元素的地址
// 并且数组的元素是不能删除的,只能够被覆盖
使用二分法是有限制的,需要满足数组为有序(本题是升序)数组,而且数组中无重复元素,一旦有重复元素,使用二分查找法返回的元素下标可能就不是唯一的。
完整代码如下
//
// Created by lwj on 2022-03-30.
//
#include <iostream>
#include <vector>
using namespace std;class Solution {
public:int search(vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;while (left <= right){int middle = (left + right) / 2;if (nums[middle] > target) {right = middle - 1;} else if (nums[middle] < target){left = middle + 1;} elsereturn middle;}return -1;}
};
int main() {int a[] = {-1, 0, 3, 5, 9, 12};vector<int> nums(a, a + sizeof(a) / sizeof(int)); // 第一个参数表示cost容器中放的是a数组,第二个参数表示是取a数组中的所有元素Solution solution;cout << solution.search(nums, 2) << endl;
}
LeetCode
力扣链接
数组在内存中的空间地址是连续的
//
// Created by lwj on 2022-03-30.
//
#include <iostream>using namespace std;
void test_arr() {int array[2][3] = {{0, 1, 2},{3, 4, 5}};cout << &array[0][0] << " " << &array[0][1] << " " << &array[0][2] << endl;cout << &array[1][0] << " " << &array[1][1] << " " << &array[1][2] << endl;
}int main() {test_arr();
}
// 输出结果为0x61fdd0 0x61fdd4 0x61fdd8
// 0x61fddc 0x61fde0 0x61fde4 可以看出数组的内存空间的地址是连续的,所以我们在删除或者增添元素的时候,就需要移动其他元素的地址
// 并且数组的元素是不能删除的,只能够被覆盖
使用二分法是有限制的,需要满足数组为有序(本题是升序)数组,而且数组中无重复元素,一旦有重复元素,使用二分查找法返回的元素下标可能就不是唯一的。
完整代码如下
//
// Created by lwj on 2022-03-30.
//
#include <iostream>
#include <vector>
using namespace std;class Solution {
public:int search(vector<int>& nums, int target) {int left = 0;int right = nums.size() - 1;while (left <= right){int middle = (left + right) / 2;if (nums[middle] > target) {right = middle - 1;} else if (nums[middle] < target){left = middle + 1;} elsereturn middle;}return -1;}
};
int main() {int a[] = {-1, 0, 3, 5, 9, 12};vector<int> nums(a, a + sizeof(a) / sizeof(int)); // 第一个参数表示cost容器中放的是a数组,第二个参数表示是取a数组中的所有元素Solution solution;cout << solution.search(nums, 2) << endl;
}
本文标签: LeetCode
版权声明:本文标题:LeetCode 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/IT/1686522226a5509.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论