今日任务:
数组理论基础
704. 二分查找,27. 移除元素
数理理论:
数组定义:数组是在内存上连续存储的相同数据类型的集合。
针对java而言,因为java没有指针概念,寻址完全交给java虚拟机,二维数组不是连续的。
704 二分查找
题目链接: . - 力扣(LeetCode)
注意点: 二分查找是针对有序数组
区间写法:左闭右闭,左闭右开区间写法,核心的关键在于区间条件保持一致。为了记混,我只操作左闭右闭写法。
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1); //这里不使用(left+right)/2的方式,是为了避免溢出
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
}
35. 搜索插入位置
题目链接:. - 力扣(LeetCode)
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid = 0;
while (left <= right) {
mid = left + ((right - left) >> 1);
if (nums[mid] < target){
left = mid + 1;
}else if (nums[mid] > target) {
right = mid - 1;
}else {
return mid;
}
}
return nums[mid] > target ? mid : mid + 1;
}
}
34. 在排序数组中查找元素的第一个和最后一个位置
题目连接:. - 力扣(LeetCode)
区间写法:左闭右闭
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int[] res = {-1, -1};
res[0] = lowerBound(nums, target);
res[1] = upperBound(nums, target);
return res;
}
public int upperBound(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
int res = -1;
while(left <= right){
int mid = left + ((right -left) >>1);
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
res = mid;
}
}
return res;
}
public int lowerBound(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
int res = -1;
while(left <= right){
int mid = left + ((right -left) >>1);
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
right = mid - 1;
res = mid;
}
}
return res;
}
}
27. 移除元素
题目连接:. - 力扣(LeetCode)
思路:思路上转换成2个数组,一个是fastindex访问的数组,一个是slowindex访问的数组,fastindex访问的数组如果值非val,则拷贝到slowindex访问的数组。
class Solution {
public int removeElement(int[] nums, int val) {
int slowIndex = 0;
int fastIndex = 0;
for (fastIndex = 0; fastIndex < nums.length; fastIndex++) { //思维上的转变,你可以认为slow维持了一个目标的数组
if (nums[fastIndex] != val) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
}
977. 有序数组的平方
题目连接:. - 力扣(LeetCode)
思路:双指针,主要的挑战在于能够想到平方后的最大值在两端,有了这个思路后改问题豁然开朗
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int left = 0;
int right = nums.length - 1;
int k = result.length - 1;
while(left <= right){
if (nums[left] * nums[left] < nums[right] * nums[right]) {
result[k--] = nums[right] * nums[right];
right--;
}else {
result[k--] = nums[left] * nums[left];
left++;
}
}
return result;
}
}