1 class Solution { 2 public int[] runningSum(int[] nums) { 3 int sum = 0 ; 4 int length = nums.length; 5 int [] res = new int[length]; 6 for(int i = 0;i < length;i++){ 7 sum = sum + nums[i]; 8 res[i] = sum; 9 } 10 return res; 11 } 12 }
1 class Solution { 2 public int[] runningSum(int[] nums) { 3 int [] res = new int[nums.length]; 4 res[0] = nums[0]; 5 for(int i = 1;i < nums.length;i++){ 6 res[i] = res[i-1] + nums[i]; 7 } 8 return res; 9 } 10 }
动态初始化 | 数组类型 [] 数组名称 = new 数组类型 [数组长度]; int [] res = new int [nums.length]; |
动态初始化(分步模式) | 数组类型[] 数组名称 = null; 数组名称 = new 数组类型 [数组长度]; int [] res = null; res = new int [nums.length]; |
静态初始化(简化格式) | 数据类型 数组名称 = {值, 值,…} int res = {1,2,3,4,5}; |
静态初始化(完整格式) | 数据类型 数组名称 = new 数据类型[] {值, 值,…} int res = new int [] {1,2,3,4,5}; |
1 public class ArrayDemo { 2 public static void main(String args[]) { 3 int data[] = null; 4 data = new int[3]; //开辟一个长度为3的数组 5 data[0] = 10; 6 data[1] = 20; 7 data[2] = 30; 8 } 9 }
1 public class ArrayDemo { 2 public static void main(String args[]) { 3 int data[] = null; 4 data = new int[3]; //开辟一个长度为3的数组 5 data[0] = 10; 6 data[1] = 20; 7 data[2] = 30; 8 } 9 }
原文:https://www.cnblogs.com/fenixG/p/13195326.html