数组相关算法题详解

1、(LeetCode1)两数之和

  链接:https://leetcode.cn/problems/two-sum/

  题目:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那两个整数,并返回它们的数组下标。

  思路:将数组中的数用两轮遍历可把所有可能的结果都取出来,每次去的时候都将两数之和和目标值进行比较,如果相等,即将对应的数存到数组中返回。

  代码实现:

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int[] result = new int[2];
 4         for(int i=0;i<nums.length;i++){
 5             for(int j=i+1;j<=num.length;j++){
 6                 if(nums[i]+nums[j]==target){
 7                     result[0] = i;
 8                     result[1] = j;
 9                     return result;
10                 }
11             }
12         }
13         return result;
14     }
15 }

2、(LeetCode88)合并两个有序数组

  链接:https://leetcode.cn/problems/merge-sorted-array/

  题目:给你两个按非递减顺序排列的整数数组nums1和nums2,另有两个整数m和n,分别表示nums1和nums2中的元素数目。请你合并nums2到nums1中,使合并后的数组同样按非递减顺序排列。

  思路:可以用一个循环,将第二个数组中的有效数字赋值到第一个数组的有效数字之后,并且第一个数组的有效数字的个数题目也给出了,就是m。将数据转移到一个数组中了,可以用JDK提供的Arrays.sort()方法,将这个数组进行排序。

  代码实现:

1 class Solution {
2     public void merge(int[] nums1, int m, int[] nums2, int n) {
3         for(int i=0;i<n;i++){
4             nums1[m+i] = nums2[i];
5         }
6         Arrays.sort(nums1);
7     }
8 }

3、(LeetCode283)移动零

  链接:https://leetcode.cn/problems/move-zeroes/

  题目:给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。

  思路:本题用到了双指针,首先定义两个指针 i 和 j ,两个指针都从下标零开始遍历, i 负责判断当前位置是否为零,若不为零则将数据复制 j 位置的数值上,然后 i 和 j 向下移位,若为零,则只将 i 移位,当 i 移到数组的末尾处,说明不为零的值都已复制完毕,然后将 j 后边的数值全都赋值为零即可。

  代码实现:

 1 class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if(nums == null){
 4             return;
 5         }
 6         int j=0;
 7         for(int i=0;i<nums.length;i++){
 8             if(nums[i]!=0){
 9                 nums[j++]=nums[i];
10             }
11         }
12         for(int i=j;i<nums.length;i++){
13             nums[i]=0;
14         }
15     }
16 }

4、(LeetCode448)找到所有数组中消失的数字

  链接:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/

  题目:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。

  思路:首先要理解题目的含义,比如当n=5的时候,这个时候数组的数字只能是在1-5之间,而自己需要找到在数组中1-5没有出现的数字,若数组为[1,2,2,4,5],因为3没在1-5里面,所以3就是答案。本题思路的话,首先数组里的数遍历出来,然后减一当做数组的下标,然后对对应位置的数字进行一定的操作,最后没有被操作的数字对应的下标就是没有出现的数字。操作的话可以对数字去相反数或者是加一个大于等于n的数,都是可以的。

  代码实现:

 1 class Solution {
 2     public List<Integer> findDisappearedNumbers(int[] nums) {
 3         int n=nums.length;
 4         for(int num:nums){
 5             int x=(num-1)%n;
 6             nums[x]+=n;
 7         }
 8         List<Integer> result = new ArrayList<Integer>();
 9         for(int i=0;i<nums.length;i++){
10             if(nums[i]<=n){
11                 result.add(i+1);
12             }
13         }
14         return result;
15     }
16 }

 

posted @ 2022-06-17 10:40  小向阳最优秀  阅读(69)  评论(0)    收藏  举报