java 使用单个循环从数组中获取所有子数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25702722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all subarrays from an array using a single loop
提问by Mano
I was wondering if there is an algorithm / pattern where someone could get/parse all subarrays of a given array using for example a simple loop.
我想知道是否有一种算法/模式可以让某人使用例如一个简单的循环来获取/解析给定数组的所有子数组。
For example: for the array myArray{0,1,2,3}
I need
例如:对于myArray{0,1,2,3}
我需要的数组
myArray(0,0)myArray(0,1),myArray(0,2),myArray(0,3)
myArray(1,1)myArray(1,2),myArray(1,3)
myArray(2,2)myArray(2,3),
myArray(3,3)
I do not wantto use something like
我不想使用类似的东西
for (i = 0; i < myArray.length; i++) {
for (j = i; j < myArray.length; j++)
{
}
}
since I want my algorithm to be faster.
因为我希望我的算法更快。
回答by BLUEPIXY
#include <stdio.h>
int main() {
int myArray[] = {0,1,2,3};
int myArrayLength = sizeof(myArray)/sizeof(*myArray);
int i, j;
for(j=i=0;i<myArrayLength;++i){
printf("(%d,%d)", myArray[j], myArray[i]);
if(i == myArrayLength -1){
i = j++;//++j - 1;
printf("\n");
}
}
return 0;
}
回答by singh.indolia
If you want to find all sub arrays of an array so first of all you should understand that sub arrays of an array should be continuous but in case of string there is not necessary of continuous for example: if we have an array like:[1,2,3], in this case there are sub arrays like: (1),(2),(3),(1,2),(2,3),(1,2,3). Program to generate sub arrays of an array :
如果你想找到一个数组的所有子数组,那么首先你应该明白数组的子数组应该是连续的,但在字符串的情况下不需要连续,例如:如果我们有一个数组:[1 ,2,3],在这种情况下有子数组,如:(1),(2),(3),(1,2),(2,3),(1,2,3)。生成数组子数组的程序:
#include<bits/stdc++.h>
using namespace std;
// Prints all subarrays in arr[0..n-1]
void subArray(int arr[], int n)
{
for (int i=0; i <n; i++)
{
for (int j=i; j<n; j++)
{
for (int k=i; k<=j; k++)
cout << arr[k] << " ";
cout << endl;
}
}
}
// Driver program
int main()
{
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "All Non-empty Subarrays\n";
subArray(arr, n);
return 0;
}
回答by alfasin
You'll need to modify the initialization of j
from j = 0
to j = i
and iterate over all the possible pairs. Example of implementation (Java):
您需要修改j
from j = 0
to的初始化j = i
并迭代所有可能的对。实现示例(Java):
public static void main(String[] args) {
int[] arr = {1,2,3,4};
List<Integer[]> res = allPairs(arr);
for(Integer[] tmp : res) {
System.out.println(Arrays.toString(tmp));
}
}
private static List<Integer[]> allPairs(int [] myArray) {
List<Integer[]> res = new ArrayList<>();
for (int i = 0; i < myArray.length; i++) {
for (int j = i; j < myArray.length; j++) {
Integer[] tmp = new Integer[2];
tmp[0] = myArray[i];
tmp[1] = myArray[j];
res.add(tmp);
}
}
return res;
}
OUTPUT
输出
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[2, 2]
[2, 3]
[2, 4]
[3, 3]
[3, 4]
[4, 4]