# 数据结构之数组

// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
// 1. Initialize
int[] a0 = new int[5];
int[] a1 = {1, 2, 3};
// 2. Get Length
System.out.println("The size of a1 is: " + a1.length);
// 3. Access Element
System.out.println("The first element is: " + a1[0]);
// 4. Iterate all Elements
System.out.print("[Version 1] The contents of a1 are:");
for (int i = 0; i < a1.length; ++i) {
System.out.print(" " + a1[i]);
}
System.out.println();
System.out.print("[Version 2] The contents of a1 are:");
for (int item: a1) {
System.out.print(" " + item);
}
System.out.println();
// 5. Modify Element
a1[0] = 4;
// 6. Sort
Arrays.sort(a1);
}
}



#### 动态数组简介

// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
// 1. initialize
List<Integer> v0 = new ArrayList<>();
List<Integer> v1;                           // v1 == null
// 2. cast an array to a vector
Integer[] a = {0, 1, 2, 3, 4};
v1 = new ArrayList<>(Arrays.asList(a));
// 3. make a copy
List<Integer> v2 = v1;                      // another reference to v1
List<Integer> v3 = new ArrayList<>(v1);     // make an actual copy of v1
// 3. get length
System.out.println("The size of v1 is: " + v1.size());;
// 4. access element
System.out.println("The first element in v1 is: " + v1.get(0));
// 5. iterate the vector
System.out.print("[Version 1] The contents of v1 are:");
for (int i = 0; i < v1.size(); ++i) {
System.out.print(" " + v1.get(i));
}
System.out.println();
System.out.print("[Version 2] The contents of v1 are:");
for (int item : v1) {
System.out.print(" " + item);
}
System.out.println();
// 6. modify element
v2.set(0, 5);       // modify v2 will actually modify v1
System.out.println("The first element in v1 is: " + v1.get(0));
v3.set(0, -1);
System.out.println("The first element in v1 is: " + v1.get(0));
// 7. sort
Collections.sort(v1);
// 8. add new element at the end of the vector
v1.add(-1);
v1.add(1, 6);
// 9. delete the last element
v1.remove(v1.size() - 1);
}
}



输入:
nums = [1, 7, 3, 6, 5, 6]



输入:
nums = [1, 2, 3]



nums 的长度范围为 [0, 10000]。

class Solution {
public int pivotIndex(int[] nums) {
int len=nums.length;
int[] left=new int[len];
int[] right=new int[len];
left[0]=nums[0];
right[len-1]=nums[len-1];
for(int i=1;i<len;i++)
{
left[i]=left[i-1]+nums[i];
}
for(int i=len-2;i>=0;i--)
{
right[i]=right[i+1]+nums[i];
}
for (int i=0;i<len;i++) {
if(left[i]==right[i])
return i;
}
return -1;
}
}


class Solution {
public int pivotIndex(int[] nums) {
int len=nums.length;
int right = 0;
int left = 0 ;
for (int i : nums) {
right+=i;
}
for(int i=0;i<len;i++)
{
right-=nums[i];
if(left==right)
return i;
left+=nums[i];
}
return -1;
}
}


#### 示例 1:

6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

#### 示例 2:

nums 的长度范围在[1, 50].

待定


posted on 2021-01-12 23:03  今今今生  阅读(57)  评论(0编辑  收藏  举报