File tree Expand file tree Collapse file tree 2 files changed +19
-21
lines changed
Expand file tree Collapse file tree 2 files changed +19
-21
lines changed Original file line number Diff line number Diff line change 11## 题目地址
2- https://leetcode-cn.com/problems/search-insert-position
2+ https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
33## 题目描述
4- 给定一个** 排序数组** 和一个目标值
5- 在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
6- 你可以假设数组中无重复元素。
7- 示例 1:
8- 输入: [ 1,3,5,6] , 5
9- 输出: 2
10- 存在以下几种情况:
11- * 目标值在数组所有元素之前
12- * 目标值等于数组中某一个元素
13- * 目标值插入数组中的位置
14- * 目标值在数组所有元素之后
4+ 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
5+ 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
6+ 示例 1:
7+ 给定数组 nums = [ 1,1,2] ,
8+ 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
159
16- ### 暴力法
17- 排序数组,找到第一个大于等于目标值的元素并返回索引,遍历结束都没有则返回最后一个位置
10+ ### 双指针
11+ 快慢两个指针,相等就跳过,不相等i++存到num [ i ]
1812``` java
19- public class SearchInsert {
20- public int search (int [] nums , int target ){
21- int length = nums. length;
22- for (int i= 0 ;i< length;i++ ){
23- if (nums[i] >= target) return i;
13+ public class Solution {
14+ public int removeDuplicates (int [] nums ) {
15+ if (nums. length == 0 ) return 0 ;
16+ int i = 0 ;
17+ for (int j = 1 ; j < nums. length; j++ ) {// 前后两个比较,j=1
18+ if (nums[j] != nums[i]) { // 不相等的就加到nums[i]中,
19+ i++ ; // i增加防止值被覆盖
20+ nums[i] = nums[j]; // 不相等的值加入nums[i]数组中
2421 }
25- return length;
2622 }
23+ return i + 1 ;
24+ }
2725}
2826```
2927#### 复杂度分析
Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ https://leetcode-cn.com/problems/remove-element/
1010你不需要考虑数组中超出新长度后面的元素。
1111
1212### 双指针
13- 快慢两个指针,相等就跳过,不相等i++ 存到num[ i]
13+ 快慢两个指针,相等就跳过,不相等nums [ j ] 存到num[ i] ,i++
1414``` java
1515public class removeElement {
1616 public int remove (int [] nums , int target ){
You can’t perform that action at this time.
0 commit comments