Two police officers sitting in their patrol car in Brooklyn were shot at point-blank range and killed on Saturday afternoon by a man who, officials said, had traveled to the city from Baltimore vowing to kill officers. The suspect then committed suicide with the same gun, the authorities said.

The officers, Wenjian Liu and Rafael Ramos, were in the car near Myrtle and Tompkins Avenues in Bedford-Stuyvesant in the shadow of a tall housing project when the gunman, Ismaaiyl Brinsley, walked up to the passenger-side window and assumed a firing stance, Police Commissioner William J. Bratton said. Mr. Brinsley shot several rounds into the heads and upper bodies of the officers, who never drew their weapons, the authorities said.

Mr. Brinsley, 28, then fled down the street and onto the platform of a nearby subway station, where he killed himself as officers closed in. The police recovered a silver semiautomatic handgun, Mr. Bratton said.

Mr. Brinsley, who had a long rap sheet of crimes that included robbery and carrying a concealed gun, is believed to have shot his former girlfriend near Baltimore before traveling to Brooklyn, the authorities said. He made statements on social media suggesting that he planned to kill police officers and was angered about the Eric Garner and Michael Brown cases.