如何降低以下代码的时间复杂度?
我必须检查查询中的单词是否存在于句子中并打印句子编号,否则打印“ -1”。
单词的顺序在查询中无关紧要。它们应该出现在句子中。
课程结果{
static boolean o=false;
public static void textQueries(List<String> sentences, List<String> queries) {
// Write your code here
String[] s, se;
ArrayList<HashSet<Integer>> arr=new ArrayList<>();
for(int i=0; i<queries.size(); i++) {
s=queries.get(i).split(" ");
HashSet<String> set=new HashSet<>(Arrays.asList(s));
for(String str : set) {
HashSet<Integer> q=new HashSet<>();
for(int j=0; j<sentences.size(); j++) {
se=sentences.get(j).split(" ");
HashSet<String> sen=new HashSet<>(Arrays.asList(se));
if(sen.contains(str)) {
q.add(j);
}
}
arr.add(q);
}
for(int d=0; d<sentences.size(); d++) {
print(d, arr);
}
if(o==false)
System.out.print("-1");
System.out.println();
arr.clear();
o=false;
}
}
public static void print(int d, ArrayList<HashSet<Integer>> arr) {
for(int a=0; a<arr.size(); a++) {
HashSet<Integer> st=arr.get(a);
if(!st.contains(d))
return;
}
o=true;
System.out.print(d+" ");
}
}
答案 0 :(得分:0)
这是我认为是改进的版本:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> sentences = Arrays.asList("a bc def", "bc, ajj");
List<String> queries = Arrays.asList("a bc def");
textQueries(sentences, queries);
}
public static void textQueries(List<String> sentences, List<String> queries) {
int counter = 0;
outer:
for (String sentence : sentences) {
System.out.println("Process sentence: " + sentence + " nr. " + (++counter));
List<String> sentenceWords = Arrays.asList((sentence.split(" ")));
for (String query : queries) {
if (sentenceWords.containsAll(Arrays.asList((query.split(" "))))) {
System.out.println(counter);
continue outer;
}
}
System.out.println(-1);
}
}
}
答案 1 :(得分:0)
<div>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<div>
<table style="display: inline-table;">
<tbody>
<tr>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<button style="margin-left: 100px;">x</button>
</td>
</tr>
<tr>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<input type="file" multiple=""><br>
<button>Add Table</button><br>
<textarea placeholder="Write some text"></textarea>
</td>
<td>
<button style="margin-left: 100px;">x</button>
</td>
</tr>
</tbody>
</table>
<button style="margin-left: 100px;">x</button>
</div>
</div>