/**
* 35. 搜索插入位置 -> 二分查询
*
* @param nums
* @param target
* @return
*/
public static int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
return i;
} else if (nums[i] >= target) {
return i;
}
if (i == nums.length - 1 && target > nums[i]) {
return nums.length;
}
}
return 0;
}
/**
* 二分查找
*
* @param nums
* @param target
* @return
*/
public static int searchInsertInGF(int[] nums, int target) {
int n = nums.length;
int left = 0, right = n - 1, ans = n;
while (left <= right) {
int mid = ((right - left) >> 1) + left;
if (target <= nums[mid]) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
/**
* 28. 实现 strStr() 函数
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/implement-strstr
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @param haystack
* @param needle
* @return
*/
public static int strStr(String haystack, String needle) {
if (null == needle || 0 == needle.length()) {
return 0;
}
return haystack.indexOf(needle);
}
/**
* 27. 移除元素
*
* @param nums
* @param val
* @return
*/
public static int removeElement(int[] nums, int val) {
int slow = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[slow++] = nums[i];
}
}
return slow;
}
/**
* 26. 删除有序数组中的重复项
*
* @param nums
* @return
*/
public static int removeDuplicates(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return nums.length;
}
int slow = 0;
for (int i = 0; i < nums.length; i++) {
if (i != 0 && nums[i] != nums[slow]) {
nums[++slow] = nums[i];
}
}
return slow + 1;
}