文章目錄
- 題目:輪轉數組
- 方法1-使用額外的數組
- 方法2-三次反轉數組
- 除自身以外數組的乘積
- 方法1-用到了除法
- 方法2-前后綴乘積法
題目:輪轉數組
原題鏈接:輪轉數組
方法1-使用額外的數組
方法1是自己寫出來的。方法2參考的別人的,方法2太👍了,不易發現這個規律
public static void rotate(int[] nums, int k) {int[] temp = new int[nums.length];int j = 0;k = k % nums.length; // 數組長度大于k時,旋轉次數取余---關鍵for (int i = nums.length - k; i < nums.length; i++) {temp[j++] = nums[i];}for (int i = 0; i < nums.length - k; i++) {temp[j++] = nums[i];}System.arraycopy(temp, 0, nums, 0, nums.length);}
方法2-三次反轉數組
private static void reverse(int[] nums, int start, int end) {while (start < end) {int temp = nums[start];nums[start] = nums[end];nums[end] = temp;start++;end--;}}public static void rotate1(int[] nums, int k) {k = k % nums.length; reverse(nums, 0, nums.length - 1);reverse(nums, 0, k - 1);reverse(nums, k, nums.length - 1);}
除自身以外數組的乘積
原題鏈接:除自身以外數組的乘積
方法1-用到了除法
當時沒看題目中不讓用除法,當時一下就想到這個思路了,哈哈哈
public static int[] productExceptSelf(int[] nums) {int temp = 1;int zero = 0;// 先看數組中0的個數 大于1則結果數組全為0 等于1則結果數組中0的位置為其他元素乘積for (int num : nums) {if (num != 0) {temp *= num;} else {zero++;if (zero > 1) return new int[nums.length];}}List<Integer> res = new ArrayList<>();for (int num : nums) {if (zero == 1) {//num==0 則當前結果數組該位置的結果為其他元素乘積res.add(num == 0 ? temp : 0);} else {res.add(temp / num);}}return res.stream().mapToInt(Integer::intValue).toArray();}
方法2-前后綴乘積法
方法2使用兩次遍歷分別計算數組元素左邊
和右邊
的乘積,從而構建出結果數組
public static int[] productExceptSelf1(int[] nums) {int n = nums.length;int[] res = new int[n];// 第一次遍歷,計算左邊所有元素的乘積res[0] = 1;for (int i = 1; i < n; i++) {res[i] = res[i - 1] * nums[i - 1];}// 第二次遍歷,計算右邊所有元素的乘積,并更新結果數組int right = 1;for (int i = n - 1; i >= 0; i--) {res[i] *= right; //res[i]是當前i左邊元素全部乘積right *= nums[i]; //用一個變量記錄當前元素右邊的所有元素乘積}return res;}
?覺得有用的可以留個關注ya~?