Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
publicclassSolution {publicint[] twoSum(int[] numbers, int target) {
String source = numbers.toString();
int[] result = newint[2];
//int l = numbers.size();
l = source.length();
int i, j;
for (i = 0; i < l; i++){
for(int j = i + 1; j < l; j++){
if(numbers[i] + numbers[j] = target){
result[0] = i;
result[1] = j;
return result;
}
}
}
}
}
Result:
Line 6: error: cannot find symbol: variable l
这个错误就是粗心大意了, 后面还有一个错误:
Line 9: error: variable j is already defined in method twoSum(int[],int)
我还是再看一遍code再提交吧
审查了一遍,又发现个错误, i的边界判定不应该是length, 而应该是length - 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
publicclassSolution {publicint[] twoSum(int[] numbers, int target) {
String source = numbers.toString();
int[] result = newint[2];
int l = source.length();
int i, j;
for (i = 0; i < l - 1; i++){
for(j = i + 1; j < l; j++){
if(numbers[i] + numbers[j] = target){
result[0] = i;
result[1] = j;
return result;
}
}
}
}
}
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.Note also that ArrayList.size() provides the number of object actually stored in the array whereas myArray.length ([]) provides the "capacity". That is, if for myArray = new int[10];, it returns 10. It is not the number of objects you've put in the array.
There are two types of Internet Protocol (IP) traffic. They are TCP or Transmission Control Protocol and UDP or User Datagram Protocol. TCP is connection oriented = once a connection is established, data can be sent bidirectional. UDP is a simpler, connectionless Internet protocol. Multiple messages are sent as packets in chunks using UDP.
Differences List
Connection:
TCP is a connection-oriented protocol.
UDP is a connectionless protocol.
Functions:
As a message makes its way across the internet from one computer to another. This is connection based.
UDP is also a protocol used in message transport or transfer. This is not connection based which means that one program can send a load of packets to another and that would be the end of the relationship.
Usage:
TCP is suited for applications that require high reliability, and transmission time is relatively less critical.
UDP is suitable for applications that need fast, efficient transmission, such as games. UDP's stateless nature is also useful for servers that answer small queries from huge numbers of clients.
Examples:
TCP: HTTP, HTTPs, FTP, SMTP, Telnet
UDP: DNS, DHCP, TFTP, SNMP, RIP, VOIP
Ordering of data packets
TCP rearranges data packets in the order specified.
UDP has no inherent order as all packets are independent of each other. If ordering is required, it has to be managed by the application layer.
Speed of transfer
TCP is slower that UDP
UDP is faster because there is no error-checking for packets.
Reliability
There is absolute guarantee that the data transferred remains intact and arrives in the same order in which it was sent.
There is no guarantee that the messages or packets sent would reach at all.
Header Size
TCP header size is 20 bytes.
UDP Header size is 8 bytes.
Common Header Fields
TCP: Source port, Destination port, Check Sum.
UDP: Source port, Destination port, Check Sum.
Streaming of Data
TCP: Data is read as a byte stream, no distinguishing indications are transmitted to signal message(segment) boundaries.
UDP: Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent.
Weight
TCP is heavy-weight. TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control.
UDP is lightweight. There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP.
Data Flow Control
TCP does flow control.
UDP does not have an option for flow control.
Error Checking
TCP does error checking
UDP does error checking too, but no recovery options.
TCP ensures a reliable and ordered delivery of a stream of bytes from user to server or vice versa. UDP is not dedicated to end to end connections and communication does not check readiness of receiver.
Reliability
TCP is more reliable since it manages message acknowledgment and retransmissions in case of lost parts. Thus there is absolutely no missing data. UDP does not ensure that communication has reached receiver since concepts of acknowledgment, time out and retransmission are not present.
Ordering
TCP transmissions are sent in a sequence and they are received in the same sequence. In the event of data segments arriving in wrong order, TCP reorders and delivers application. In the case of UDP, sent message sequence may not be maintained when it reaches receiving application. There is absolutely no way of predicting the order in which message will be received.
Connection
TCP is a heavy weight connection requiring three packets for a socket connection and handles congestion control and reliability. UDP is a lightweight transport layer designed atop an IP. There are no tracking connections or ordering of messages.
Method of transfer
TCP reads data as a byte stream and message is transmitted to segment boundaries. UDP messages are packets which are sent individually and on arrival are checked for their integrity. Packets have defined boundaries while ata stream has none.
How TCP and UDP work
A TCP connection is established via a three way handshake, which is a process of initiating and acknowledging a connection. Once the connection is established data transfer can begin. After transmission, the connection is terminated by closing of all established virtual circuits.
UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing reliability, ordering, or data integrity. Thus, UDP provides an unreliable service datagrams may arrive out of order, appear duplicated, or go missing without notice. UDP assumes that error checking and correction is either not necessary or performed in the application, avoiding the overhead of such processing at the network interface level. Unlike TCP, UDP is compatible with packet broadcasts(sending to all on local network) and multicasting(seng to all subscribers).
Different Applications of TCP and UDP
Web browsing, email and file transfer are common applications that make use of TCP. TCP is used to control segment size, rate of data exchange, flow control and network congestion. TCP is preferred where error correction facilities are required at network interface level. UDP is largely used by time sensitive applications as well as by servers that answer small queries from huge number of clients. UDP is compatible with packet broadcast - sending to all on a network and multicasting - sending to all subscribers. UDP is commonly used in Domain Name System, Voice over IP, Trivial File Transfer Protocol and online games.
Threads, of course, allow for multi-threading. A common example of the advantage of multithreading is the fact that you can have a word processor that prints a document using a background thread, but at the same time another thread is running that accepts user input, so that you can type up a new document.
If we were dealing with an application that uses only one thread, then the application would only be able to do one thing at a time – so printing and responding to user input at the same time would not be possible in a single threaded application.
Each process has it’s own address space, but the threads within the same process share that address space. Threads also share any other resources within that process. This means that it’s very easy to share data amongst threads, but it’s also easy for the threads to step on each other, which can lead to bad things.
Multithreaded programs must be carefully programmed to prevent those bad things from happening. Sections of code that modify data structures shared by multiple threads are called critical sections. When a critical section is running in one thread it’s extremely important that no other thread be allowed into that critical section. This is called synchronization, which we wont get into any further over here. But, the point is that multithreading requires careful programming.
Also, context switching between threads is generally less expensive than in processes. And finally, the overhead (the cost of communication) between threads is very low relative to processes.
SUMMARY
Threads are easier to create than processes since they
don't require a separate address space.
Multithreading requires careful programming since threads
share data strucures that should only be modified by one thread
at a time. Unlike threads, processes don't share the same
address space.
Threads are considered lightweight because they use far
less resources than processes.
Processes are independent of each other. Threads, since they
share the same address space are interdependent, so caution
must be taken so that different threads don't step on each other. This is really another way of stating #2 above.
This is just a plug, from me, for you to know about processes, threads and
concurrency issues. A lot of interviewers ask about that stuff, and it's
pretty fundamental, so you should know it. Know about locks and mutexes and
semaphores and monitors and how they work. Know about deadlock and livelock
and how to avoid them. Know what resources a processes needs, and a thread
needs, and how context switching works, and how it's initiated by the
operating system and underlying hardware. Know a little about scheduling.
The world is rapidly moving towards multi-core, and you'll be a dinosaur in
a real hurry if you don't understand the fundamentals of "modern" (which is
to say, "kinda broken") concurrency constructs.
A process is an executing instance of an application. What does that mean? Well, for example, when you double-click the Microsoft Word icon, you start a process that runs Word. A thread is a path of execution within a process. Also, a process can contain multiple threads. When you start Word, the operating system creates a process and begins executing the primary thread of that process.
Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
Threads are an operating environment feature, rather than a CPU feature(though the CPU typically has operations that make threads efficient). Erlang uses the term "process" because it does not expose a
shared-memory multiprogramming model. Calling them "threads" would imply that they have shared memory.
A process is an executing instance of an application. What does that mean? Well, for example, when you double-click the Microsoft Word icon, you start a process that runs Word. A thread is a path of execution within a process. Also, a process can contain multiple threads. When you start Word, the operating system creates a process and begins executing the primary thread of that process.
It’s important to note that a thread can do anything a process can do. But since a process can consist of multiple threads, a thread could be considered a ‘lightweight’ process. Thus, the essential difference between a thread and a process is the work that each one is used to accomplish. Threads are used for small tasks, whereas processes are used for more ‘heavyweight’ tasks – basically the execution of applications.
Another difference between a thread and a process is that threads within the same process share the same address space, whereas different processes do not. This allows threads to read from and write to the same data structures and variables, and also facilitates communication between threads. Communication between processes – also known as IPC, or inter-process communication – is quite difficult and resource-intensive.
static members belong to the class instead of a specific instance.
It means that only one instance of a static field exists even if you create a million instances of the class or you don't create any. It will be shared by all instances.
Since static methods also do not belong to a specific instance, they can't refer to instance members (how would you know which instance Hello class you want to refer to?). static members can only refer to static members. Instance members can, of course access static members.
Side note: Of course, static members can access instance members through an object reference.
这里sendEmail()有一点tricky的地方,就是用了final variable, final String username & final String password, 这是因为sendEmail()method中的inner class使用了这两个argument. 原因:
There are two main reasons you might want to mark an argument final. First, if you're planning on using the argument in an anonymous inner class, then you must mark it final so that it can be referenced in that class. This is actually a pretty common use case for marking arguments final.
The other common reason to mark arguments final is to prevent yourself from accidentally overwriting them. If you really don't want to change the arguments, then perhaps you should mark them final so that if you actually do, you'll get the error at compile-time rather than finding out at runtime that your code has a bug.