问题描述
我编写了以下代码来输出输入中不同单词的数量,以及每个不同单词在输入中出现的次数。
我使用了 list append 和 count 方法并获得了所需的输出,但是由于超时错误,一些测试用例没有执行。
n = int(input())
ar = []
for _ in range(n):
ar.append(input().rstrip())
def wordOrder(n,ar):
w_list =[] #list contains the number of repition of words
u_list =[] #list eliminates the duplicates while maintaining the same order
for i in ar:
if i not in u_list:
u_list.append(i)
w_list.append(ar.count(i))
return w_list
result = wordOrder(n,ar)
print(len(result))
print(*result,sep=' ')
所以,我尝试使用 deque 而不是 list 认为这可能是由于 list append 方法的 O(n) 时间复杂度问题。但即使在使用 deque 后,我也遇到同样的错误。
我的问题是问题是由于时间复杂度问题还是其他一些因素造成的?如果有人能解释采用何种技术来避免超时错误,那就太好了。
样本输入:
4
bcdef
abcdefg
bcde
bcdef
样本输出:
3
2 1 1
解决方法
这段代码很适合我
from collections import Counter
a=[]
for i in range(int(input())):
a.append(input())
x = Counter(a)
print(len(x.keys()))
print(*x.values())
,
虽然只使用 Counter() 幸运地解决了这个问题,但使用 OrderedDict() 来维护所提供输入的现有顺序是安全的。因此,下面的代码应该在所有类似的情况下都能正常工作,并且不会带来任何我想要的“超时错误”。
import "package:flutter/material.dart";
class Login extends StatelessWidget {
final color = Colors.white;
final darkColor = Colors.black;
final primaryColor = Colors.redAccent;
_buttons(double height,double width,String text,Color buttonColor,Color textColor) {
return Container(
height: height,width: width,decoration: BoxDecoration(
color: color,borderRadius: BorderRadius.circular(30),boxShadow: [
BoxShadow(
color: Colors.grey[400],blurRadius: 2,offset: Offset(0,5),)
]),child: RaisedButton(
color: buttonColor,onPressed: () {},shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),),child: Text(
text,style: TextStyle(color: textColor,fontSize: 14),);
}
@override
Widget build(BuildContext context) {
return Scaffold(
//resizeToAvoidBottomInset: false,//backgroundColor: kWhite,body: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * .52,color: Colors.white,child: Stack(
overflow: Overflow.visible,children: [
Container(
width: MediaQuery.of(context).size.width,height: MediaQuery.of(context).size.height * .50,decoration: BoxDecoration(
color: Colors.blueAccent,borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(32),bottomRight: Radius.circular(32),Align(
alignment: Alignment.bottomLeft,child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 50),child: Row(
//crossAxisAlignment: CrossAxisAlignment,mainAxisAlignment: MainAxisAlignment.spaceAround,children: [
_buttons(30,120,'LOGIN',Colors.blueGrey[900],color),_buttons(30,'SIGNUP',color,Colors.grey[400]),],SafeArea(child: Text("hi"))
],);
}
}